当前位置:   article > 正文

springcloud gateway 集成eureka_gateway集成eureka

gateway集成eureka
  1. gateway:
  2. springcloud子项目与spring无缝整合,上手简单,异步非阻塞,性能比zuul1好一点
  3. 功能与zuul类似:权限认证,限流,路由分发,熔断,响应处理
  4. 总结一下gateway的特性:
  5. 1).动态路由
  6. 2).易于编写的 Predicates(断言) 和 Filters(过滤器)
  7. 3).限流
  8. 4).集成 Eureka 默认路由
  9. 5).集成 Hystrix 断路器
  10. 6).路由超时

springcloud集成gateway代码地址 github: https://github.com/475cheng/gateway-demo-cheng

springboot接入gateway
  1. 1.引入pom.xml
  2. ```xml
  3. <project>
  4. <parent>
  5. <groupId>org.springframework.boot</groupId>
  6. <artifactId>spring-boot-starter-parent</artifactId>
  7. <version>2.0.5.RELEASE</version>
  8. </parent>
  9. <dependencyManagement>
  10. <dependencies>
  11. <dependency>
  12. <groupId>org.springframework.cloud</groupId>
  13. <artifactId>spring-cloud-dependencies</artifactId>
  14. <version>Finchley.SR1</version>
  15. <type>pom</type>
  16. <scope>import</scope>
  17. </dependency>
  18. </dependencies>
  19. </dependencyManagement>
  20. <dependencies>
  21. <dependency>
  22. <groupId>org.springframework.cloud</groupId>
  23. <artifactId>spring-cloud-starter-gateway</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.cloud</groupId>
  27. <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
  28. </dependency>
  29. </dependencies>
  30. </project>
  31. ```
  32. 2.添加路由规则,有两种形式,代码或者配置文件
  33. 1).代码形式
  34. ```java
  35. @Configuration
  36. public class RouteLocatorBean {
  37. public static String httpUriA = "http://www.baidu.com";
  38. public static String httpUriB = "http://www.baidu.com/endpoint/endpointB";
  39. @Bean
  40. public RouteLocator myRoutes(RouteLocatorBuilder builder) {
  41. return builder.routes()
  42. .route(p -> p
  43. .path("/getmessage")
  44. .filters(f -> f.hystrix(config -> config //404不会触发断路,服务停止才会触发forward
  45. .setName("myCommandName")
  46. .setFallbackUri("forward:/fallback"))) //1.对请求路径为/getmessage的,路由到httpUriB这个地址,如果这个地址服务挂掉,进行路由熔断,重定到这个地址/fallback
  47. .uri(httpUriB)) //uri这里可以是域名,它会自动将请求路径追加到域名后面
  48. .route(p -> p
  49. .path("/endpointA")
  50. .filters(f -> f.prefixPath("/endpoint"))
  51. .uri(httpUriA)) //2.对于请求路径为/endpointA的,对于请求路径包装,前缀添加/endpoint,最终访问路径为http://www.baidu.com/endpoint/endpointA
  52. .route(p -> p
  53. .query("name", "shen")
  54. .filters(f -> f.addRequestHeader("username","test"))
  55. .uri(httpUriB)) //3.对于请求中携带的参数为http://baidu.com?name=shen的,最终路由到httpUriB这个地址,并且在请求头中添加username=test
  56. .route(p -> p
  57. .path("/fallback") //4.如果gateway服务没有fallback端点,但是别的服务有fallback端点,可以这样配置
  58. .uri("http://localhost:8888")) //那么上面熔断的路由都会请求带这个地址http://localhost:8888/fallback
  59. .build();
  60. }
  61. }
  62. ```
  63. 2). 配置文件形式 以application.yml格式为例
  64. ```application.yml
  65. spring:
  66. cloud:
  67. gateway:
  68. enabled: true //默认为true启动网关,如果项目中引用的jar包而不想启用网关,可以改为false
  69. routes:
  70. - id: path_route_hys
  71. uri: http://localhost:8888/endpoint/endpointB
  72. predicates:
  73. - Path=/getmessage //特别注意:- Path =/getmessage 这样格式的话,gateway的所有配置都会失效
  74. filters:
  75. - name: Hystrix
  76. args:
  77. name: test_hystrix
  78. fallbackUri: forward:/fallback
  79. - id: path_route_pre
  80. uri: http://localhost:8888
  81. predicates:
  82. - Path=/endpointA
  83. filters:
  84. - PrefixPath=/endpoint
  85. - id: query_route
  86. uri: http://localhost:8888/endpoint/endpointB
  87. predicates:
  88. - Query=name, shen
  89. filters:
  90. - AddRequestHeader=username, test
  91. hystrix:
  92. command:
  93. test_hystrix: //这个地方是上面hystrix的name,timeout默认是1s, default为全局配置默认
  94. execution:
  95. isolation:
  96. thread:
  97. timeoutInMilliseconds: 9000
  98. ```
  99. 3.集成Eureka
  100. 1).pom添加
  101. ```pom.xml
  102. <dependency>
  103. <groupId>org.springframework.cloud</groupId>
  104. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  105. </dependency>
  106. 接口用于重试
  107. <dependency>
  108. <groupId>org.springframework.retry</groupId>
  109. <artifactId>spring-retry</artifactId>
  110. </dependency>
  111. ```
  112. 2).以配置文件形式为例 yml格式为例
  113. ```yml
  114. spring:
  115. cloud:
  116. loadbalancer:
  117. retry:
  118. enabled: true //开启失败重试
  119. gateway:
  120. discovery:
  121. locator:
  122. enabled: true //当访问http://网关地址/服务名称(大写)/**地址会自动转发到http://服务名称(大写)/**地址,如果为false就不会自动转发
  123. lowerCaseServiceId: true //为true表示服务名称(小写)
  124. routes:
  125. - id: service-hi
  126. uri: lb://SERVICE-HI //lb代表从注册中心获取服务,后面接的就是你需要转发到的服务名称 不能填uri只能是服务名称
  127. predicates:
  128. - Path=/demo/**
  129. filters:
  130. - name: Retry
  131. args:
  132. retries: 3 //在Eureka注册列表中有一个节点挂掉了,在短时间内,列表没有更新,还会调用挂掉的节点,可以通过失败重试调用其他节点
  133. statuses: BAD_GATEWAY
  134. eureka:
  135. instance:
  136. prefer-ip-address: true
  137. client:
  138. service-url:
  139. defaultZone: http://123456@master:8761/eureka/
  140. ```
  141. 4.gateway 自定义全局过滤器 (如:token过滤器)
  142. 创建完全局过滤器,加上@Component注解就会生效
  143. ```java
  144. @Component
  145. public class TokenFilter implements GlobalFilter, Ordered {
  146. Logger logger=LoggerFactory.getLogger( TokenFilter.class );
  147. @Override
  148. public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
  149. String token = exchange.getRequest().getQueryParams().getFirst("token");
  150. if (token == null || token.isEmpty()) {
  151. logger.info( "token is empty..." );
  152. exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
  153. return exchange.getResponse().setComplete();
  154. }
  155. return chain.filter(exchange);
  156. }
  157. @Override
  158. public int getOrder() {
  159. return -100;
  160. }
  161. }
  162. ```
  163. 5.gateway 自定义过滤器filter
  164. 1).创建自定义过滤器
  165. ```java
  166. public class RequestTimeGatewayFilterFactory extends AbstractGatewayFilterFactory<RequestTimeGatewayFilterFactory.Config> { //泛型用静态内部类
  167. private static final Log log = LogFactory.getLog(GatewayFilter.class);
  168. private static final String REQUEST_TIME_BEGIN = "requestTimeBegin";
  169. private static final String KEY = "withParams";
  170. @Override
  171. public List<String> shortcutFieldOrder() {
  172. return Arrays.asList(KEY);
  173. }
  174. public RequestTimeGatewayFilterFactory() {
  175. super(Config.class);
  176. }
  177. @Override
  178. public GatewayFilter apply(Config config) {
  179. return (exchange, chain) -> {
  180. exchange.getAttributes().put(REQUEST_TIME_BEGIN, System.currentTimeMillis());
  181. return chain.filter(exchange).then(
  182. Mono.fromRunnable(() -> {
  183. Long startTime = exchange.getAttribute(REQUEST_TIME_BEGIN);
  184. if (startTime != null) {
  185. StringBuilder sb = new StringBuilder(exchange.getRequest().getURI().getRawPath())
  186. .append(": ")
  187. .append(System.currentTimeMillis() - startTime)
  188. .append("ms");
  189. if (config.isWithParams()) {
  190. sb.append(" params:").append(exchange.getRequest().getQueryParams());
  191. }
  192. log.info(sb.toString());
  193. }
  194. })
  195. );
  196. };
  197. }
  198. public static class Config {
  199. private boolean withParams;
  200. public boolean isWithParams() {
  201. return withParams;
  202. }
  203. public void setWithParams(boolean withParams) {
  204. this.withParams = withParams;
  205. }
  206. }
  207. }
  208. ```
  209. 2).添加bean中
  210. ```java
  211. @Configuration
  212. public class FilterBeanFactory {
  213. @Bean
  214. public RequestTimeGatewayFilterFactory elapsedGatewayFilterFactory() {
  215. return new RequestTimeGatewayFilterFactory();
  216. }
  217. }
  218. ```
  219. 3).引用自定义过滤器
  220. ```yml
  221. spring:
  222. cloud:
  223. gateway:
  224. routes:
  225. - id: add_request_header_route
  226. uri: http://localhost:8888/endpoint/endpointA
  227. filters:
  228. - RequestTime=true //此处为因为自定义过滤器
  229. ```
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号