1.Feign 基本使用
Feign只是对ribbon 进行了一层调用,ribbon的负载均衡啥的fegin都有。简化了调用规则,使得代码更加简洁。
这边特别简单直接代码见
使用的jar
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
启动类上加注解,这边还有其他注解,加深一下印象
//开始fegin的使用
@EnableFeignClients
//允许去eureka上去获取地址
@EnableDiscoveryClient
//注册到eureka的服务
@EnableEurekaClient
@SpringBootApplication
//name 设置服务提供方服务名称
//@RibbonClient(name = "EUREKA-CLIENT",configuration = MyRule.class)
public class ConsumerApp {
public static void main(String[] args) {
SpringApplication.run(ConsumerApp.class,args);
}
}
最关键的就是加上调用远程的接口类
注意这边的接口上的GetMapping的地址是调用服务的客户端controller的地址,我们是消费端,这个不要搞错。
//这边的value 就是注册到eureka上的应用名称
@FeignClient(value = "EUREKA-CLIENT")
public interface ConsumerFeignClient {
//这边需要注意的是这个url是controller的全路径,
// 不仅仅是方法上的还要拼接类上的路径
@GetMapping("/company/findCompany/{id}")
public CompanyInfo find3(@PathVariable int id);
}
1.1 Feign超时机制
这边默认超时是1s钟时间,不给我返回我就报错。那么我的方法就是这么慢,你爱用不用哦。那么我们超时时间也是可以商量的。
ribbon:
ConnectTimeout: 1000 #1秒连不上不用了
ReadTimeout : 4000 #4秒不给我返回不用了
1.2 Feign 日志功能
这边就是记录你每次调用feign的日志信息,feign记录的日志级别只能是debug ,其他的日志级别不能记录。
首先设置日志记录级别
logging:
level:
com.zx: debug
配置类
@Configuration
public class FeignLog {
@Bean
public Logger.Level feignlevel(){
return Logger.Level.FULL;//日志的全部信息
}
}
在feign接口里面使用这个类,那么再次运行的时候,就会有日志信息打印出来。
//这边的value 就是注册到eureka上的应用名称
@FeignClient(value = "EUREKA-CLIENT",configuration = FeignLog.class)
public interface ConsumerFeignClient {
//这边需要注意的是这个url是controller的全路径,
// 不仅仅是方法上的还要拼接类上的路径
@GetMapping("/company/findCompany/{id}")
public CompanyInfo find3(@PathVariable int id);
}
2022-03-27 22:49:23.068 DEBUG 9125 --- [nio-8889-exec-1] c.zx.consumer.Feign.ConsumerFeignClient : [ConsumerFeignClient#find3] <--- HTTP/1.1 200 (3150ms)
2022-03-27 22:49:23.069 DEBUG 9125 --- [nio-8889-exec-1] c.zx.consumer.Feign.ConsumerFeignClient : [ConsumerFeignClient#find3] content-type: application/json;charset=UTF-8
2022-03-27 22:49:23.069 DEBUG 9125 --- [nio-8889-exec-1] c.zx.consumer.Feign.ConsumerFeignClient : [ConsumerFeignClient#find3] date: Sun, 27 Mar 2022 14:49:23 GMT
2022-03-27 22:49:23.070 DEBUG 9125 --- [nio-8889-exec-1] c.zx.consumer.Feign.ConsumerFeignClient : [ConsumerFeignClient#find3] transfer-encoding: chunked
2022-03-27 22:49:23.070 DEBUG 9125 --- [nio-8889-exec-1] c.zx.consumer.Feign.ConsumerFeignClient : [ConsumerFeignClient#find3]
2022-03-27 22:49:23.076 DEBUG 9125 --- [nio-8889-exec-1] c.zx.consumer.Feign.ConsumerFeignClient : [ConsumerFeignClient#find3] {"name":"baidu"}
2022-03-27 22:49:23.076 DEBUG 9125 --- [nio-8889-exec-1] c.zx.consumer.Feign.ConsumerFeignClient : [ConsumerFeignClient#find3] <--- END HTTP (16-byte body)
2. Hystrix 熔断器
微服务保护机制,防止雪崩,雪崩意思就是因为一个服务的不可用导致很多服务接二连三的不可用
Hystrix的四大功能: 隔离、降级、熔断、限流
隔离 | 1.线程池隔离 这边的意思就是每个服务我都给一个固定数量的线程池,反正不管怎么用,就这么多,也不会影响到其他服务的线程 2.信号量隔离 这边规定的就是每个服务最大的服务量,多了就不服务。这样的话也可以防止其他服务没有资源可用的情况 |
降级 | 降级的意思就是,我如果不给你返回正常的数据信息,那么我就换一种方式返回给你,比如服务器忙。反正不给你数据我找个借口,这就是降级。当然这边无论是服务的提供方还是消费方都应该提供相应的降级方案。 |
熔断 | 就是当服务器压力过大,我直接拉闸,后面压力小了我在逐渐开放服务 |
限流 | 顾名思义 |
2.1 Hystrix 基本使用
2.1.1启动类配置
//客户端注册
@EnableEurekaClient
@SpringBootApplication
@EnableCircuitBreaker//开启Hystrix
public class EurekaProvider {
public static void main(String[] args) {
SpringApplication.run(EurekaProvider.class,args);
}
}
2.1.2方法降级配置
这边触发降级的场景有两个 第一个是方法报错,会调用降级方法,第二个就是超时,如果一个方法1s不回复那么就会触发降级方法,如果延长时间可以通过如下方法设置超时时间
@GetMapping("/findCompany/{id}")
@HystrixCommand(fallbackMethod = "findCompany_fallback",commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "4000")
})
public CompanyInfo findCompany(@PathVariable int id) throws InterruptedException {
System.out.println(port);
Thread.sleep(3000);
return companyService.findCompanyInfo(id);
}
private CompanyInfo findCompany_fallback(int id) throws InterruptedException {
System.out.println("降级了~~~");
return new CompanyInfo();
}
2.1.3 feign 集成hystrix
配置降级方法
/**
* 这个就是降级类,这边需要注意的就是需要吧这个类交给
* spring容器管理
*/
@Component
public class ConsumerFeignFallback implements ConsumerFeignClient{
@Override
public CompanyInfo find3(int id) {
System.out.println("客户端降级了!");
return new CompanyInfo();
}
}
feign 配置降级类,fallback属性
//这边的value 就是注册到eureka上的应用名称
@FeignClient(value = "EUREKA-CLIENT",configuration = FeignLog.class,fallback = ConsumerFeignFallback.class)
public interface ConsumerFeignClient {
//这边需要注意的是这个url是controller的全路径,
// 不仅仅是方法上的还要拼接类上的路径
@GetMapping("/company/findCompany/{id}")
public CompanyInfo find3(@PathVariable int id);
}
2.2 Hystrix 熔断
这边的熔断机制需要了解,Hystrix有一个断路器,这个断路器有三种状态,关闭、开启、半开启
他的工作机制就是当某段时间内某个方法次数过多,那么断路器就打开,并且拒绝了所有的请求,这个断路器会开启一定的时常进入半开启状态,目的就是校验一下这个方法恢复了没,如果还是出错那么继续进入开启状态。
熔断配置
@GetMapping("/findCompany/{id}")
@HystrixCommand(fallbackMethod = "findCompany_fallback",commandProperties = {
//超时时间默认是1s
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "4000"),
//熔断时间,默认是5s
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "5000"),
//熔断时间内失败的次数,默认是20次
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "20"),
//失败率默认是50%
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "50")
})
public CompanyInfo findCompany(@PathVariable int id) throws InterruptedException {
if(id==1){
int a = 1/0;
}
System.out.println(port);
//Thread.sleep(3000);
return companyService.findCompanyInfo(id);
}
2.3 Hystrix 监控
主要是监控Hystrix的一些功能,就是监控一些借口的状态的模块,其实不是那么重要有兴趣可以了解一下
2.3.1 搭建监控工程
pom文件
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-turbine</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
配置文件
server:
port: 7777
turbine:
combine-host-port: true
app-config: EUREKA-CONSUMER,EUREKA-CLIENT。#在eureka 上注册的服务,并且需要被监控的
cluster-name-expression: "'default'"
aggregator:
cluster-config: default
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
spring:
application:
name: hystrix-m
启动类
@SpringBootApplication
@EnableEurekaClient
@EnableTurbine//开启聚合监控,就是把一个一个单个仪表盘给他搞起来一起看
@EnableHystrixDashboard//开启单个仪表盘监控
public class HystrixApp {
public static void main(String[] args) {
SpringApplication.run(HystrixApp.class,args);
}
}
2.3.2 被监控服务需要的配置
配置文件
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
然后配置类上需要加上注解,并且需要注入一个bean 对象
//开始fegin的使用
@EnableFeignClients
//允许去eureka上去获取地址
@EnableDiscoveryClient
//注册到eureka的服务
@EnableEurekaClient
@SpringBootApplication
@EnableHystrixDashboard//开启单个仪表盘
//name 设置服务提供方服务名称
//@RibbonClient(name = "EUREKA-CLIENT",configuration = MyRule.class)
public class ConsumerApp {
public static void main(String[] args) {
SpringApplication.run(ConsumerApp.class,args);
}
@Bean
public ServletRegistrationBean getServlet(){
HystrixMetricsStreamServlet hystrixMetricsStreamServlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(hystrixMetricsStreamServlet);
servletRegistrationBean.setLoadOnStartup(1);
servletRegistrationBean.addUrlMappings("/actuator/hystrix.stream");
servletRegistrationBean.setName("HystrixMetricsStreamServlet");
return servletRegistrationBean;
}
}
2.3.3 访问具体的页面
我的页面地址是http://localhost:7777/hystrix/monitor
这边输入的东西呢可以在你监控服务启动的时候控制台有展现,留意一下
把红框内的内容复制到监控的搜索框,那么监控服务就搭建完成了。
3 Gateway网关
网关的作用,如果一个页面的一个点击事件需要调用十几个微服务方法,那我一个一个调用是不是贼麻烦,网关的作用就诞生了,我前端页面直接访问网关,告诉网关你要干嘛,网关帮你一一调用!
3.1 基本使用
没什么东西简单过一下
pom 包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
配置文件,这边是静态路由的方式,eureka 还没有用到
server:
port: 80
spring:
application:
name: Gateway
cloud:
gateway:
routes: #转发规则
- id: eureka-client #唯一标识
uri: http://localhost:8880/ #访问端口ip,这边写死就是静态路由
predicates:
- Path=/company/** #访问筛选路径,这边就是以这个开头的就走id是eureka-client这个转发规则
启动类
@SpringBootApplication
@EnableEurekaClient
public class GatewayServer {
public static void main(String[] args) {
SpringApplication.run(GatewayServer.class,args);
}
}
3.1.1 动态路由
就是从eureka上拿应用名称实现网关uri的加载,配置文件如下,这边配置了可以用为服务名称访问的功能
server:
port: 80
spring:
application:
name: Gateway
cloud:
gateway:
routes: #转发规则
- id: eureka-client #唯一标识
#访问端口ip,这边写死就是静态路由
#uri: http://localhost:8880/
uri: lb://EUREKA-CLIENT
predicates:
- Path=/company/** #访问筛选路径,这边就是以这个开头的就走id是eureka-client这个转发规则
discovery:
locator:
enabled: true #允许用注册中心的为服务名称访问
lower-case-service-id: true #使用小写,大写是不行的
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
3.2 过滤器
这个东西知道怎么用的就行,简而言之就是,请求过来之后我可以把在这个请求里面加点参数,减少点参数,就是对请求进行相对应的逻辑处理。
3.2.1 局部过滤器
这边其实就是配置文件里面添加,我这边filter里面加了一个username的参数,用的方法是AddRequestParameter 当然还有很多其他方法,具体获取这个username 字段,是在下游的方法的controller,这边有一点需要注意的是,如果你用微服务的名称走的话是,不会添加这个username的。
spring:
application:
name: Gateway
cloud:
gateway:
routes: #转发规则
- id: eureka-client #唯一标识
#访问端口ip,这边写死就是静态路由
#uri: http://localhost:8880/
uri: lb://EUREKA-CLIENT
predicates:
- Path=/company/** #访问筛选路径,这边就是以这个开头的就走id是eureka-client这个转发规则
filters:
- AddRequestParameter=username,ttt
3.2.2 全局过滤器
这边在javaweb里面应该也用到过。功能差不多,直接看实现
@Component
public class Myfilter implements GlobalFilter, Ordered {
/**
* 过滤器的拦截方法
* 并且进行相关逻辑处理
* @param exchange
* @param chain
* @return
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
System.out.println("我拦个女的折磨");
return chain.filter(exchange);//放行
}
/**
* 这边的方法是过滤器的执行顺序
* @return
*/
@Override
public int getOrder() {
return 0;
}
}