SpringCloud五大组件
五大组件:Eureka(注册中心),
Ribbon/Feign(负载均衡),
Zuul(网关),
Config(配置中心),
Hystrix(熔断器)
注:本文章较长,但是五大组件全都包含
新建一个父模块,导包,包含SpringCloud以及SpringBoot的包
------注册中心
1.1在SpringCloud官网 找到Eureka(How to includ Eureka)
1.2新建模块Eureka,导包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
1.
server:
port: 1000
eureka:
instance:
hostname: localhost #主机
client:
registerWithEureka: false #禁止注册中心向自己注册
fetchRegistry: false #禁止注册中心拉取注册地址清单
serviceUrl: #微服务向注册中心注册的地址
defaultZone: http://localhost:1000/eureka/
1.4在主配置类上打标签 @EnableEurekaServer 开启Eureka事务
package cn.itsource.springboot;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(EurekaApplication.class).web(true).run(args);
}
}
高可用集群
2.1为什么使用Eureka高可用集群?
答:当只有一个EurekaServer,如果挂掉了,那么整个微服务都不可用,所以要进行集群
2.2
在“我的电脑”C:\Windows\System32\drivers\etc这个路径下 添加两个peer1和peer2
127.0.0.1 peer1
127.0.0.1 peer2
2.3 配置如下
spring:
profiles:
active: peer1
---
server:
port: 1000
eureka:
instance:
hostname: peer1 #主机
client:
registerWithEureka: false #禁止注册中心向自己注册
fetchRegistry: false #禁止注册中心拉取注册地址清单
serviceUrl: #微服务向注册中心注册的地址
defaultZone: http://peer2:1001/eureka/
spring:
profiles: peer1
---
server:
port: 1001
eureka:
instance:
hostname: peer2 #主机
client:
registerWithEureka: false #禁止注册中心向自己注册
fetchRegistry: false #禁止注册中心拉取注册地址清单
serviceUrl: #微服务向注册中心注册的地址
defaultZone: http://peer1:1000/eureka/
spring:
profiles: peer2
ribbon是负载均衡器,是基于RestTemplate ,它赋予了RestTemplate 负载均衡的能力
在客户端order中使用Ribbon
3.1导入jar包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
3.2 写一个类,里面写RestTemplate方法
RestTemplate简介: pring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接, 我们只需要传入url及返回值类型即可。相较于之前常用的HttpClient,RestTemplate是一种更优雅的调用RESTful服务的方式。
package ;
import ;
import ;
import ;
import ;
@Configuration
public class BeanConfig {
//交给Bean管理
//@LoadBalanced :让RestTemplate 有负载均衡的能力
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
3.3主配置类
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@SpringBootApplication
@RestController
@Import()
public class OrderApplication {
public static void main(String[] args) {
new SpringApplicationBuilder().web(true).run(args);
}
}
3.4 Controller层方法
@GetMapping("/order/user/{id}")
public User getUserById(@PathVariable("id") Long id){
//String url = "http://localhost:2000/user/"+id;
String url = "http://user-server/user/"+id;
User user = (url, );
return user;
}
3.5
eureka:
client:
serviceUrl:
defaultZone: http://peer1:1000/eureka/,http://peer2:1001/eureka/
instance:
instance-id: first-one
prefer-ip-address: true
server:
port: 2000
spring:
application:
name: order
简介:Feign是基于Ribbon,同样具有负载均衡的能力
4.1引入Feign的jar包
<dependency>
<groupId></groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
4.2 配置类打上标签 @EnableFeignClients(“”) feignclient是接口类的包名
package ;
import ;
import ;
import ;
@SpringBootApplication
@EnableFeignClients("")
public class OrderApplication {
public static void main(String[] args) {
new SpringApplicationBuilder().web(true).run(args);
}
}
4.3 写一个接口类
package ;
import ;
import ;
import ;
import ;
import ;
//该客户端接口用来调用用户服务(user-server)
// http://user-server/userserver/user/11 -> ribbon
@FeignClient(value = "customer",fallback = )
public interface UserFeignClient {
//调用根据id获取用户的接口
@GetMapping("/userserver/user/{id}")
User getUserById(@PathVariable("id") Long id);
}
4.4 再写一个实现类
package ;
import ;
import ;
import ;
@Component
public class UserFeignClientFallback implements UserFeignClient {
@Override
public User getUserById(Long id) {
//返回托底数据
return new User(-1L,"null","用户服务获取失败");
}
}
4.5 Controller控制层调用接口类
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
//订单服务,消费者
@RestController
@RequestMapping("/orderserver")
public class OrderServerController {
@Autowired
private UserFeignClient userFeignClient ;
//浏览器调用,根据id获取用户 : 有负载均衡
@GetMapping("/user/{id}")
public User getUserById(@PathVariable("id")Long id){
return (id);
}
}
4.6
eureka:
client:
serviceUrl:
defaultZone: http://peer1:1000/eureka/,http://peer2:1001/eureka/
instance:
instance-id: order-second
prefer-ip-address: true
server:
port: 2001
spring:
application:
name: order-second
5.1 导包
<dependency>
<groupId></groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
5.2 配置类打上注解标签(开启Hystrix)
@EnableCircuitBreaker
5.3 Controller控制层 (需在公共类上写一个AjaxResult)
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@RestController
@RequestMapping("/orderserver")
public class OrderController {
@Autowired
private RestTemplate restTemplate;
//这是订单服务,调用用户服务
@HystrixCommand(fallbackMethod = "getUserByIdFallback")
@GetMapping("/user/{id}")
public AjaxResult getUserById(@PathVariable("id")Long id){
String url = "http://customer/userserver/user/"+id;
//customer是yml配置中名
//userserver是控制层的mapping
User user = (url, );
AjaxResult ajaxResult = new AjaxResult();
(user);
return ajaxResult;
}
//编写降级方法
public AjaxResult getUserByIdFallback(@PathVariable("id")Long id){
AjaxResult ajaxResult = new AjaxResult();
(false);
("抱歉,订单服务不可能");
return ajaxResult;
}
}
5.4
eureka:
client:
serviceUrl:
defaultZone: http://peer1:1000/eureka/,http://peer2:1001/eureka/
instance:
instance-id: first-one
prefer-ip-address: true
server:
port: 2000
spring:
application:
name: order
网关
6.1 导入jar包
<dependency>
<groupId></groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
6.2 主配置类上打注解标签 @EnableZuulProxy//开启zuul网关
package ;
import ;
import ;
import ;
import ;
@EnableZuulProxy//开启zuul网关
@SpringBootApplication
@RestController
public class ZuulApplication {
public static void main(String[] args) {
new SpringApplicationBuilder().web(true).run(args);
}
}
6.3
eureka:
client:
serviceUrl:
defaultZone: http://peer1:1000/eureka/,http://peer2:1001/eureka/
instance:
instance-id: first-one
prefer-ip-address: true
server:
port: 4000
spring:
application:
name: zuul-server
zuul:
routes:
order: "/order/**" #别名---order是订单服务yml中的名字
prefix: "/pre" #前缀
#浏览器访问格式:http://localhost:4000/pre/order/orderserver/user/10
6.4 写一个过滤器的类,继承ZuulFilter,实现登录检查
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
public class ZuulByFilter extends ZuulFilter{
//过滤器的类型 PRE_TYPE
@Override
public String filterType() {
return "pre";
}
//过滤器的顺序
@Override
public int filterOrder() {
return 1;
}
@Override
public boolean shouldFilter() {
//获取请求上下文
RequestContext currentContext = ();
//获取请求对象
HttpServletRequest request = ();
//获取请求的地址
String requestURI = ();
//如果包含了login,则返回false
if (().contains("LOGIN")){
return false;
}
return true;
}
//执行run方法-----中心方法
@Override
public Object run() throws ZuulException {
//获取上下文对象
RequestContext currentContext = ();
//获取对象
HttpServletRequest request = ();
//获取相应对象
HttpServletResponse response = ();
//获取响应的数据格式
("application/json;charset:utf-8");
//获取请求头x-token
String token = ("x-token");
//如果不存在请求头,则让重新登录
if ((token)){
HashMap<String,String> map = new HashMap<>();
("success", "false");
("errorMessage","麻烦请登录" );
(false);
}
return null;
}
}
7.1 导入jar包
<dependency>
<groupId></groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
7.2 主配置类打上注解标签
package ;
import ;
import ;
import ;
//@EnableDiscoveryClient
//@EnableConfigServer :开启配置中心
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication5000 {
public static void main(String[] args) {
();
}
}
7.3 (放在码云仓库中)
server:
port: 5000
spring:
application:
name: config-server
#码云仓库地址
cloud:
config:
server:
git:
uri: /xxxxx/ #码云仓库
username: xxxxx
password: xxxxx
eureka:
client:
serviceUrl:
defaultZone: http://peer1:1000/eureka/,http://peer2:1001/eureka/
instance:
prefer-ip-address: true #使用ip注册到注册中心
instance-id: config-server:5000 #指定服务的id
7.4 浏览器访问地址: localhost:5000/
实际要看码云中仓库名