cloud-02-feign-gateway-bus
1. Feign应用
Feign
的作用 : 使用Feign
实现user-consumer
代码中调用服务
分析步骤:
- 导入启动器依赖;
- 开启
Feign
功能;
- 编写
Feign
客户端;
- 编写一个处理器
ConsumerFeignController
,注入Feign
客户端并使用;
- 测试
Feign
主要作用:自动根据参数拼接http
请求地址。
启动器依赖;
pom.xml(user-comsumer)
1 2 3 4
| <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
|
Feign
客户端:
UserClient.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package com.nateshao.consumer.client;
import com.nateshao.consumer.pojo.User; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(value = "user-service") public interface UserClient {
@GetMapping("/user/{id}") User queryById(@PathVariable Long id); }
|
ComsumerFeignController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| package com.nateshao.consumer.controller;
import com.nateshao.consumer.client.UserClient; import com.nateshao.consumer.pojo.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
@RestController @RequestMapping("cf") public class ComsumerFeignController {
@Autowired private UserClient userClient;
@GetMapping("/{id}") public User queryById(@PathVariable Long id){
return userClient.queryById(id); } }
|
分别启动**userApplication.java , EurekaServiceApplication.java , ComsumerApplication.java
**服务
2. Feign负载均衡及熔断
目标:可以配置Feign
内置ribbon
配置项和Hystrix
熔断的Fallback
配置
分析:
都可以通过配置项在Feign
中开启使用。
小结:
在服务消费工程user-consumer
中的配置文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| ribbon: ConnectTimeout: 1000 ReadTimeout: 2000 MaxAutoRetries: 0 MaxAutoRetriesNextServer: 0 OkToRetryOnAllOperations: false feign: hystrix: enabled: true compression: request: enabled: true mime-types: text/html,application/xml,application/json min-request-size: 2048 response: enabled: true logging: level: com.nateshao: debug
|
UserController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| package com.nateshao.user.controller;
import com.nateshao.user.pojo.User; import com.nateshao.user.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
@RestController @RequestMapping("/user") public class UserController {
..... try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }
...... } }
|
设置超时之后,起作用了:
1 2 3
| @FeignClient(value = "user-service",fallback = UserClientFallback.class) public interface UserClient {
|
1 2 3
| feign: hystrix: enabled: true
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| package com.nateshao.consumer.client.fallback;
import com.nateshao.consumer.client.UserClient; import com.nateshao.consumer.pojo.User; import org.springframework.stereotype.Component;
@Component public class UserClientFallback implements UserClient {
@Override public User queryById(Long id) { User user = new User(); user.setId(id); user.setUserName("用户异常"); return user; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| feign: hystrix: enabled: true compression: request: enabled: true mime-types: text/html,application/xml,application/json min-request-size: 2048 response: enabled: true logging: level: com.nateshao: debug
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package com.nateshao.consumer.feigin; import feign.Logger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
@Configuration public class FeignConfig { @Bean Logger.Level feignLoggerLevel(){ return Logger.Level.FULL; } }
|
配置UserClient.java
1 2 3
| @FeignClient(value = "user-service",fallback = UserClientFallback.class,configuration = FeignConfig.class) public interface UserClient {
|
请求访问结果
控制台输出:
在feign
日志级别的配置控制台输出的内容:
1 2 3 4 5 6 7 8 9 10 11
| 2020-08-31 00:41:52.873 DEBUG 8028 --- [-user-service-3] com.nateshao.consumer.client.UserClient : [UserClient#queryById] ---> GET http://user-service/user/4 HTTP/1.1 2020-08-31 00:41:52.873 DEBUG 8028 --- [-user-service-3] com.nateshao.consumer.client.UserClient : [UserClient#queryById] Accept-Encoding: deflate 2020-08-31 00:41:52.874 DEBUG 8028 --- [-user-service-3] com.nateshao.consumer.client.UserClient : [UserClient#queryById] Accept-Encoding: gzip 2020-08-31 00:41:52.874 DEBUG 8028 --- [-user-service-3] com.nateshao.consumer.client.UserClient : [UserClient#queryById] ---> END HTTP (0-byte body) 2020-08-31 00:41:52.882 DEBUG 8028 --- [-user-service-3] com.nateshao.consumer.client.UserClient : [UserClient#queryById] <--- HTTP/1.1 200 (7ms) 2020-08-31 00:41:52.882 DEBUG 8028 --- [-user-service-3] com.nateshao.consumer.client.UserClient : [UserClient#queryById] content-type: application/json;charset=UTF-8 2020-08-31 00:41:52.882 DEBUG 8028 --- [-user-service-3] com.nateshao.consumer.client.UserClient : [UserClient#queryById] date: Sun, 30 Aug 2020 16:41:52 GMT 2020-08-31 00:41:52.882 DEBUG 8028 --- [-user-service-3] com.nateshao.consumer.client.UserClient : [UserClient#queryById] transfer-encoding: chunked 2020-08-31 00:41:52.882 DEBUG 8028 --- [-user-service-3] com.nateshao.consumer.client.UserClient : [UserClient#queryById] 2020-08-31 00:41:52.882 DEBUG 8028 --- [-user-service-3] com.nateshao.consumer.client.UserClient : [UserClient#queryById] {"id":4,"userName":"zhangliu","password":"123456","name":"张六","age":20,"sex":1,"birthday":"1996-08-31T16:00:00.000+0000","created":"2014-09-19T08:56:04.000+0000","updated":"2014-09-19T08:56:04.000+0000","note":"张六同学在理工学Java"} 2020-08-31 00:41:52.882 DEBUG 8028 --- [-user-service-3] com.nateshao.consumer.client.UserClient : [UserClient#queryById] <--- END HTTP (245-byte body)
|
3. SpringCloud Gateway网关简介
Spring Cloud Gateway
网关的作用
Spring Cloud Gateway
的核心就是一系列的过滤器,可以将客户端的请求转发到不同的微服务。主要作用:过滤和路由。
4. Spring Cloud Gateway入门
搭建网关服务工程测试网关服务作用
分析:
需求:通过网关系统user-gateway
将包含有 /user
的请求 路由到 http://127.0.0.1:9091/user/用户id
实现步骤:
创建工程;
添加启动器依赖;
编写启动引导类和配置文件;
修改配置文件,设置路由信息;
启动测试
路由指向 http://127.0.0.1:10010/user/8 –> http://127.0.0.1:9091/user/8
1 2 3 4 5 6 7 8 9 10
| <dependencies> <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> </dependencies>
|
- 配置文件application.yml(user-gateway)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| server: port: 10010 spring: application: name: api-gateway cloud: gateway: routes: - id: user-service-route uri: http://127.0.0.1:9091 predicates: - Path=/user/**
eureka: client: service-url: defaultZone: http://127.0.0.1:10086/eureka instance: prefer-ip-address: true
|
5. 面向服务的路由
如果将路由服务地址写死明显是不合理的;在Spring Cloud Gateway
中可以通过配置动态路由解决。
lb 之后编写的服务名必须要在eureka中注册才能使用
6. 路由前缀处理
可以对请求到网关服务的地址添加或去除前缀
分析:
提供服务的地址:http://127.0.0.1:9091/user/8
- 添加前缀:对请求地址添加前缀路径之后再作为代理的服务地址;
http://127.0.0.1:10010/8 –> http://127.0.0.1:9091/user/8 添加前缀路径/user
- 去除前缀:将请求地址中路径去除一些前缀路径之后再作为代理的服务地址;
http://127.0.0.1:10010/api/user/8 –> http://127.0.0.1:9091/user/8 去除前缀路径/api
总结:
客户端的请求地址与微服务的服务地址如果不一致的时候,可以通过配置路径过滤器实现路径前缀的添加和去除。
7. 过滤器简介
Gateway
默认过滤器的用法和过滤器类型
小结:
- 用法:在配置文件中指定要使用的过滤器名称;
- 类型:局部、全局;
- 使用场景:请求鉴权、异常处理、记录调用时长等。
8. 自定义局部过滤器
按照默认过滤器编写并配置一个自定义局部过滤器,该过滤器可以通过配置文件中的参数名称获取请求的参数值
分析:
需求:在过滤器(MyParamGatewayFilterFactory
)中将http://localhost:10010/api/user/8?name=itcast中的参数**name**的值获取到并输出到控制台;并且参数名是可变的,也就是不一定每次都是**name**;需要可以通过配置过滤器的时候做到配置参数名。
实现步骤:
- 配置过滤器;
- 编写过滤器;
- 测试
小结:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| package com.nateshao.gateway.filter;
import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.stereotype.Component;
import java.util.Arrays; import java.util.List;
@Component public class MyParamGatewayFilterFactory extends AbstractGatewayFilterFactory<MyParamGatewayFilterFactory.Config> {
static final String PARAM_NAME = "param";
public MyParamGatewayFilterFactory() { super(Config.class); }
public List<String> shortcutFieldOrder() { return Arrays.asList(PARAM_NAME); }
@Override public GatewayFilter apply(Config config) { return (exchange, chain) -> { ServerHttpRequest request = exchange.getRequest(); if(request.getQueryParams().containsKey(config.param)){ request.getQueryParams().get(config.param). forEach(value -> System.out.printf("------------局部过滤器--------%s = %s------", config.param, value)); } return chain.filter(exchange); }; }
public static class Config{ private String param;
public String getParam() { return param; }
public void setParam(String param) { this.param = param; } } }
|
访问:http://localhost:10010/api/user/8?name=nateshao
9. 自定义全局过滤器
定义一个全局过滤器检查请求中是否携带有token参数
分析:
需求:编写全局过滤器,在过滤器中检查请求地址是否携带token参数。如果token参数的值存在则放行;如果token的参数值为空或者不存在则设置返回的状态码为:未授权也不再执行下去。
实现步骤:
- 编写全局过滤器;
- 测试
小结:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| package com.nateshao.gateway.filter;
import org.apache.commons.lang.StringUtils; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono;
@Component public class MyGlobalFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { System.out.println("--------------全局过滤器MyGlobalFilter------------------"); String token = exchange.getRequest().getQueryParams().getFirst("token"); if(StringUtils.isBlank(token)){ exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); return exchange.getResponse().setComplete(); } return chain.filter(exchange); }
@Override public int getOrder() { return 1; } }
|
10. Gateway其它配置说明
目标:Gateway
网关的负载均衡和熔断参数配置
小结:
网关服务配置文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| server: port: 10010 spring: application: name: api-gateway cloud: gateway: routes: - id: user-service-route uri: lb://user-service predicates: - Path=/api/user/** filters: - StripPrefix=1 - MyParam=name default-filters: - AddResponseHeader=X-Response-Foo, Bar - AddResponseHeader=abc-myname,heima globalcors: corsConfigurations: '[/**]': allowedOrigins: - "http://docs.spring.io" allowedMethods: - GET eureka: client: service-url: defaultZone: http://127.0.0.1:10086/eureka instance: prefer-ip-address: true hystrix: command: default: execution: isolation: thread: timeoutInMilliseconds: 6000 ribbon: ConnectTimeout: 1000 ReadTimeout: 2000 MaxAutoRetries: 0 MaxAutoRetriesNextServer: 0
|
Gateway
网关一般直接给终端请求使用;Feign
一般用在微服务之间调用。
11. Spring Cloud Config分布式配置中心简介
目标:分布式配置中心的作用
小结:
spring cloud config
作用:可以通过修改在git仓库中的配置文件实现其它所有微服务的配置文件的修改。
12. 搭建配置中心微服务
创建码云的远程公开git
仓库,搭建配置中心微服务config-server
分析:
- 创建
git
仓库:在码云上创建仓库
- 搭建配置中心
config-server
:使用spring boot
方式搭建和配置
小结:
1 2 3 4 5 6 7 8 9 10
| <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> </dependencies>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| server: port: 12000 spring: application: name: config-server cloud: config: server: git: uri: https://gitee.com/nateshao/nateshao-cloud-config.git eureka: client: service-url: defaultZone: http://127.0.0.1:10086/eureka
|
在gitee中修改了配置文件会在配置中心服务及时更新。
13. 获取配置中心配置
目标:改造用户微服务user-service
,配置文件信息不再由微服务项目提供,而是从配置中心获取
分析:
需求:将服务提供工程user-service
的application.yml
配置文件删除,修改为从配置中心config-server
中获取。
实现步骤:
- 添加启动器依赖;
- 修改配置文件;
- 启动测试
小结:
将原来的application.yml
删除;然后添加bootstrap.yml
配置文件,该文件也是spring boot的默认配置文件,其内容经常配置一些项目中固定的配置项。如果是项目经常变动的应该配置到application.yml
中,现在使用了配置中心则应该配置到git
仓库中对于的配置文件。
1 2 3 4 5
| <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> <version>2.1.1.RELEASE</version> </dependency>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| spring: cloud: config: name: user profile: dev label: master discovery: enabled: true service-id: config-server
eureka: client: service-url: defaultZone: http://127.0.0.1:10086/eureka
|
14. Spring Cloud Bus简介
Spring Cloud Bus
作用:将git
仓库的配置文件更新,在不重启系统的情况下实现及时同步到各个微服务。
15. Spring Cloud Bus应用
启动RabbitMQ
通过修改码云中的配置文件后发送Post
请求实现及时更新用户微服务中的配置项
分析:
需求:在码云的git仓库中修改user-dev.yml
配置文件,实现不重启user-service
的情况下可以及时更新配置文件。
实现步骤:
- 启动
RabbitMQ
;
- 修改配置中心
config-server
;
- 修改服务提供工程
user-service
;
- 测试
小结:
1 2 3 4 5 6 7 8 9
| <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-bus</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-stream-binder-rabbit</artifactId> </dependency>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| server: port: 12000 spring: application: name: config-server cloud: config: server: git: uri: https://gitee.com/goheima/heima-config.git rabbitmq: host: localhost port: 5672 username: guest password: guest eureka: client: service-url: defaultZone: http://127.0.0.1:10086/eureka management: endpoints: web: exposure: include: bus-refresh
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-bus</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-stream-binder-rabbit</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
|
1 2 3 4 5 6 7
| rabbitmq: host: localhost port: 5672 username: guest password: guest
|
16. Spring Cloud 体系技术综合应用说明
了解Spring Cloud
中的Eureka、GateWay、Config、Bus、Feign
等技术的综合应用
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1210331079@qq.com