springcloud脚手架搭建(四)---zuul网关搭建

分手后的思念是犯贱 2022-06-02 09:36 271阅读 0赞

1.引入pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.gameley</groupId>
  5. <artifactId>gateway-service</artifactId>
  6. <version>1.0.0-SNAPSHOT</version>
  7. <packaging>jar</packaging>
  8. <name>gateway-service</name>
  9. <description>Demo project for Spring Boot</description>
  10. <parent>
  11. <groupId>com.gameley</groupId>
  12. <artifactId>adplatform</artifactId>
  13. <version>1.0.0-SNAPSHOT</version>
  14. </parent>
  15. <dependencies>
  16. <dependency>
  17. <groupId>org.springframework.cloud</groupId>
  18. <artifactId>spring-cloud-starter-eureka</artifactId>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.springframework.cloud</groupId>
  22. <artifactId>spring-cloud-starter-zuul</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-web</artifactId>
  27. <exclusions>
  28. <exclusion>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-tomcat</artifactId>
  31. </exclusion>
  32. </exclusions>
  33. </dependency>
  34. <dependency>
  35. <groupId>org.springframework.boot</groupId>
  36. <artifactId>spring-boot-starter-jetty</artifactId>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework.boot</groupId>
  40. <artifactId>spring-boot-starter-actuator</artifactId>
  41. </dependency>
  42. <!--<dependency>-->
  43. <!--<groupId>org.springframework.cloud</groupId>-->
  44. <!--<artifactId>spring-cloud-sleuth-zipkin-stream</artifactId>-->
  45. <!--</dependency>-->
  46. <!--<dependency>-->
  47. <!--<groupId>org.springframework.cloud</groupId>-->
  48. <!--<artifactId>spring-cloud-starter-stream-rabbit</artifactId>-->
  49. <!--</dependency>-->
  50. <dependency>
  51. <groupId>io.jsonwebtoken</groupId>
  52. <artifactId>jjwt</artifactId>
  53. <version>0.6.0</version>
  54. </dependency>
  55. <dependency>
  56. <groupId>com.alibaba</groupId>
  57. <artifactId>fastjson</artifactId>
  58. <version>1.2.33</version>
  59. </dependency>
  60. <dependency>
  61. <groupId>org.projectlombok</groupId>
  62. <artifactId>lombok</artifactId>
  63. <version>1.16.14</version>
  64. <scope>provided</scope>
  65. </dependency>
  66. <dependency>
  67. <groupId>com.gameley</groupId>
  68. <artifactId>gameley-common</artifactId>
  69. <version>1.0</version>
  70. </dependency>
  71. <dependency>
  72. <groupId>org.springframework.cloud</groupId>
  73. <artifactId>spring-cloud-starter-feign</artifactId>
  74. </dependency>
  75. <dependency>
  76. <groupId>org.springframework.boot</groupId>
  77. <artifactId>spring-boot-starter-aop</artifactId>
  78. </dependency>
  79. <!--<dependency>-->
  80. <!--<groupId>org.springframework.cloud</groupId>-->
  81. <!--<artifactId>spring-cloud-starter-zipkin</artifactId>-->
  82. <!--<version>RELEASE</version>-->
  83. <!--</dependency>-->
  84. </dependencies>
  85. <build>
  86. <plugins>
  87. <plugin>
  88. <groupId>org.springframework.boot</groupId>
  89. <artifactId>spring-boot-maven-plugin</artifactId>
  90. </plugin>
  91. </plugins>
  92. </build>
  93. </project>

2.配置zuul:

  1. zuul:
  2. routes:
  3. api-a:
  4. path: /user-api/**
  5. serviceId: user-service
  6. api-b:
  7. path: /gameley-auth/**
  8. serviceId: gameley-auth
  9. prefix: /api #为zuul设置一个公共的前缀

3.创建springboot启动类

  1. package com.gameley;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
  5. import org.springframework.cloud.netflix.feign.EnableFeignClients;
  6. import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.web.cors.CorsConfiguration;
  9. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  10. import org.springframework.web.filter.CorsFilter;
  11. @SpringBootApplication
  12. @EnableZuulProxy
  13. @EnableEurekaClient
  14. @EnableFeignClients
  15. public class GatewayServiceApplication {
  16. public static void main(String[] args) {
  17. SpringApplication.run(GatewayServiceApplication.class, args);
  18. }
  19. /** * 解决跨域问题 * @return */
  20. @Bean
  21. public CorsFilter corsFilter() {
  22. final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  23. final CorsConfiguration config = new CorsConfiguration();
  24. config.setAllowCredentials(true); // 允许cookies跨域
  25. config.addAllowedOrigin("*");// #允许向该服务器提交请求的URI,*表示全部允许
  26. config.addAllowedHeader("*");// #允许访问的头信息,*表示全部
  27. config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
  28. config.addAllowedMethod("*");// 允许提交请求的方法,*表示全部允许,也可以单独设置GET、PUT等
  29. config.addAllowedMethod("HEAD");
  30. config.addAllowedMethod("GET");// 允许Get的请求方法
  31. config.addAllowedMethod("PUT");
  32. config.addAllowedMethod("POST");
  33. config.addAllowedMethod("DELETE");
  34. config.addAllowedMethod("PATCH");
  35. source.registerCorsConfiguration("/**", config);
  36. return new CorsFilter(source);
  37. }
  38. }

4.配置登录拦截器

  1. package com.gameley.filter;
  2. import com.alibaba.fastjson.JSON;
  3. import com.gameley.bean.Audience;
  4. import com.gameley.bean.JwtInfo;
  5. import com.gameley.common.constant.RestCodeConstants;
  6. import com.gameley.common.msg.auth.TokenErrorResponse;
  7. import com.gameley.feign.ElementService;
  8. import com.gameley.utils.JwtHelper;
  9. import com.netflix.zuul.ZuulFilter;
  10. import com.netflix.zuul.context.RequestContext;
  11. import io.jsonwebtoken.Claims;
  12. import lombok.extern.slf4j.Slf4j;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.beans.factory.annotation.Value;
  15. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  16. import org.springframework.stereotype.Component;
  17. import javax.servlet.http.HttpServletRequest;
  18. @EnableConfigurationProperties(Audience.class)
  19. @Slf4j
  20. @Component
  21. public class loginfiler extends ZuulFilter {
  22. @Autowired
  23. ElementService iUserService;
  24. @Override
  25. public String filterType() {
  26. return "pre";
  27. }
  28. @Override
  29. public int filterOrder() {
  30. return 0;
  31. }
  32. @Value("${zuul.prefix}")
  33. private String zuulPrefix;
  34. @Value("${gate.ignore.startWith}")
  35. private String startWith;
  36. @Autowired
  37. private Audience audience;
  38. @Override
  39. public boolean shouldFilter() {
  40. return true;
  41. }
  42. @Override
  43. public Object run() {
  44. RequestContext ctx = RequestContext.getCurrentContext();
  45. HttpServletRequest request = ctx.getRequest();
  46. final String requesturi=request.getRequestURI().substring(zuulPrefix.length());
  47. String token=request.getHeader("token");
  48. String client=request.getHeader("client");
  49. //不进行拦截的地址
  50. if(isStartWith(requesturi)){
  51. return null;
  52. }
  53. /** * 未登录,踢出 */
  54. if(token==null||client==null){
  55. ctx.setSendZuulResponse(false);// 过滤该请求,不对其进行路由
  56. ctx.setResponseStatusCode(RestCodeConstants.TOKEN_ERROR_CODE);// 返回错误码
  57. ctx.setResponseBody("fail token");// 返回错误内容
  58. ctx.set("isSuccess", false);
  59. return null;
  60. }
  61. try {
  62. JwtInfo jwtInfo=new JwtInfo();
  63. jwtInfo.setToken(token);
  64. jwtInfo.setClientId(audience.getClientId());
  65. jwtInfo.setExpiresSecond(audience.getExpiresSecond());
  66. jwtInfo.setName(audience.getName());
  67. JwtHelper jwtHelper=new JwtHelper();
  68. jwtHelper.setJwtInfo(jwtInfo);
  69. Claims claims = jwtHelper.parseJWT(token, audience.getBase64Secret());
  70. Claims clientClaims = jwtHelper.parseJWT(client, audience.getClient64Secret());
  71. if(claims==null||clientClaims==null){
  72. /** * 暂不使用后台自动刷新,改为前端页面定时自动拉取刷新 */
  73. setFailedRequest("token过期", RestCodeConstants.TOKEN_ERROR_CODE);
  74. return null;
  75. // String refreshToken=jwtInfo.getToken();
  76. // ctx.addZuulRequestHeader("token",refreshToken);
  77. // ctx.addZuulResponseHeader("token",refreshToken);
  78. }else {
  79. ctx.addZuulRequestHeader("token",token);
  80. }
  81. } catch (Exception e) {
  82. setFailedRequest(JSON.toJSONString(new TokenErrorResponse(e.getMessage())), RestCodeConstants.TOKEN_ERROR_CODE);
  83. return null;
  84. }
  85. return null;
  86. }
  87. /** * URI是否以什么打头 * * @param requestUri * @return */
  88. private boolean isStartWith(String requestUri) {
  89. boolean flag = false;
  90. for (String s : startWith.split(",")) {
  91. if (requestUri.startsWith(s)) {
  92. return true;
  93. }
  94. }
  95. return flag;
  96. }
  97. /** * 网关抛异常 * * @param body * @param code */
  98. private void setFailedRequest(String body, int code) {
  99. log.debug("Reporting error ({}): {}", code, body);
  100. RequestContext ctx = RequestContext.getCurrentContext();
  101. ctx.setResponseStatusCode(code);
  102. if (ctx.getResponseBody() == null) {
  103. ctx.setResponseBody(body);
  104. ctx.setSendZuulResponse(false);
  105. }
  106. }
  107. }

5.备注:这里登录使用的为jwt-token(https://www.jianshu.com/p/576dbf44b2ae)

发表评论

表情:
评论列表 (有 0 条评论,271人围观)

还没有评论,来说两句吧...

相关阅读