SpringCloud的zuul 网关的使用

SpringlCoud的zuul 网关的使用

1.先搭建eurekaServer

《1》创建一个springboot项目,application.yml中加入一下配置:


 
 
  1. #端口号
  2. server:
  3. port: 9002
  4. #eureka的name
  5. spring:
  6. application:
  7. name: EurekaServer2
  8. #eureak:搭建eureka集群
  9. eureka:
  10. instance:
  11. hostname: peer2
  12. client:
  13. register-with-eureka: false
  14. fetch-registry: false
  15. serviceUrl:
  16. # 服务的地址
  17. defaultZone: http: //localhost:9002/eureka/

《2》.引入的pom


 
 
  1. <dependency>
  2. <groupId>org.springframework.boot </groupId>
  3. <artifactId>spring-boot-starter-web </artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.cloud </groupId>
  7. <artifactId>spring-cloud-starter-netflix-eureka-server </artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>org.springframework.boot </groupId>
  11. <artifactId>spring-boot-starter-test </artifactId>
  12. <scope>test </scope>
  13. </dependency>

《3》添加注解


 
 
  1. @SpringBootApplication
  2. @EnableEurekaServer
  3. public class EurekaApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(EurekaApplication.class, args);
  6. }
  7. }

《4》.eureks已经搭建完成,我们可以访问 http://localhost:9002 就ok了,出现下面的页面就好了

 

2.搭建一个普通的springboot项目一个接口


 
 
  1. @RestController
  2. public class ZuulTestController {
  3. @GetMapping("zuul/c")
  4. @ResponseBody
  5. public String getZuul(){
  6. return "aaa";
  7. }
  8. }

3.搭建zuul服务

《1》application.yml的配置


 
 
  1. server:
  2. port: 9001
  3. spring:
  4. application:
  5. name: zuul
  6. zuul:
  7. routes:
  8. api -a:
  9. path: /ribbon/**
  10. serviceId: service-ribbon
  11. api-b:
  12. path: /feign/**
  13. serviceId: service-feign
  14. api-c:
  15. path: /zuulService/**
  16. serviceId: demo1 #注册到eureka的name
  17. eureka:
  18. client:
  19. service-url:
  20. defaultZone: http://localhost:9002/eureka/
  21. instance:
  22. prefer-ip-address: true
  23. ribbon:
  24. ReadTimeout: 3000
  25. ConnectTimeout: 3000
  26. eager-load:
  27. enabled: false
  28. zuul:
  29. host:
  30. connect-timeout-millis: 10000
  31. socket-timeout-millis: 10000
  32. hystrix:
  33. command:
  34. default:
  35. execution:
  36. isolation:
  37. thread:
  38. timeout-in-milliseconds: 10000

《2》添加注解


 
 
  1. @EnableEurekaClient
  2. @EnableZuulProxy
  3. @SpringBootApplication
  4. public class ZuulApplication {
  5. public static void main(String[] args) {
  6. SpringApplication.run(ZuulApplication.class, args);
  7. }
  8. }

《3》pom


 
 
  1. <dependency>
  2. <groupId>org.springframework.boot </groupId>
  3. <artifactId>spring-boot-starter-web </artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.cloud </groupId>
  7. <artifactId>spring-cloud-starter-netflix-zuul </artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>org.springframework.boot </groupId>
  11. <artifactId>spring-boot-starter-test </artifactId>
  12. <scope>test </scope>
  13. </dependency>
  14. <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka -->
  15. <dependency>
  16. <groupId>org.springframework.cloud </groupId>
  17. <artifactId>spring-cloud-starter-eureka </artifactId>
  18. <version>1.4.5.RELEASE </version>
  19. </dependency>

《4》额外的前置拦截《不做拦截可以不写》


 
 
  1. import com.netflix.zuul.ZuulFilter;
  2. import com.netflix.zuul.context.RequestContext;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.stereotype.Component;
  6. import org.springframework.util.StringUtils;
  7. import sun.misc.BASE64Decoder;
  8. import javax.crypto.Cipher;
  9. import javax.crypto.KeyGenerator;
  10. import javax.crypto.SecretKey;
  11. import javax.crypto.spec.SecretKeySpec;
  12. import javax.servlet.http.HttpServletRequest;
  13. import java.io.BufferedReader;
  14. import java.io.IOException;
  15. import java.security.SecureRandom;
  16. import java.util.Objects;
  17. @Component
  18. public class RequestFilter extends ZuulFilter {
  19. private static Logger log = LoggerFactory.getLogger(RequestFilter.class);
  20. @Override
  21. public String filterType() {
  22. //前置过滤器
  23. return "pre";
  24. }
  25. @Override
  26. public int filterOrder() {
  27. //优先级,数字越大,优先级越低
  28. return 0;
  29. }
  30. @Override
  31. public boolean shouldFilter() {
  32. //是否执行该过滤器,true代表需要过滤
  33. return true;
  34. }
  35. @Override
  36. public Object run() {
  37. RequestContext ctx = RequestContext.getCurrentContext();
  38. log.info( ""+ctx);
  39. HttpServletRequest request = ctx.getRequest();
  40. log.info( "send {} request to {}", request.getMethod(), request.getRequestURL().toString());
  41. //获取传来的参数accessToken
  42. Object accessToken = request.getParameter( "accessToken");
  43. try {
  44. BufferedReader br = request.getReader();
  45. } catch (IOException e) {
  46. e.printStackTrace();
  47. }
  48. String header = request.getHeader( "accessToken");
  49. log.info( "aaaa="+header);
  50. if(!StringUtils.isEmpty(header)) {
  51. String token = AESDncode( "yy",header);
  52. if(token.equals( "xxx")){
  53. return null;
  54. }
  55. }
  56. log.warn( "access token is empty");
  57. //过滤该请求,不往下级服务去转发请求,到此结束
  58. ctx.setSendZuulResponse( false);
  59. ctx.setResponseStatusCode( 401);
  60. ctx.setResponseBody( "{\"result\":\"accessToken为空!\"}");
  61. ctx.getResponse().setContentType( "text/html;charset=UTF-8");
  62. return null;
  63. // //如果有token,则进行路由转发
  64. // log.info("access token ok");
  65. // //这里return的值没有意义,zuul框架没有使用该返回值
  66. // return null;
  67. }
  68. public String AESDncode(String encodeRules,String content){
  69. try {
  70. //1.构造密钥生成器,指定为AES算法,不区分大小写
  71. KeyGenerator keygen=KeyGenerator.getInstance( "AES");
  72. //2.根据ecnodeRules规则初始化密钥生成器
  73. //生成一个128位的随机源,根据传入的字节数组
  74. keygen.init( 128, new SecureRandom(encodeRules.getBytes()));
  75. //3.产生原始对称密钥
  76. SecretKey original_key=keygen.generateKey();
  77. //4.获得原始对称密钥的字节数组
  78. byte [] raw=original_key.getEncoded();
  79. //5.根据字节数组生成AES密钥
  80. SecretKey key= new SecretKeySpec(raw, "AES");
  81. //6.根据指定算法AES自成密码器
  82. Cipher cipher=Cipher.getInstance( "AES");
  83. //7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二个参数为使用的KEY
  84. cipher.init(Cipher.DECRYPT_MODE, key);
  85. //8.将加密并编码后的内容解码成字节数组
  86. byte [] byte_content= new BASE64Decoder().decodeBuffer(content);
  87. /*
  88. * 解密
  89. */
  90. byte [] byte_decode=cipher.doFinal(byte_content);
  91. String AES_decode= new String(byte_decode, "utf-8");
  92. return AES_decode;
  93. } catch (Exception e) {
  94. e.printStackTrace();
  95. }
  96. //如果有错就返加nulll
  97. return null;
  98. }
  99. }

4.写一个对外暴露的controller通过resttemple访问


 
 
  1. @RestController
  2. public class ZuulTestController {
  3. @Autowired
  4. private RestTemplate restTemplate;
  5. @GetMapping( "zuul/test/resourte")
  6. @ResponseBody
  7. public String getZuulResult(HttpServletRequest request){
  8. String url = "http://localhost:9001/zuulService/zuul/c";
  9. HttpHeaders headers = new HttpHeaders();
  10. headers.setContentType(MediaType.APPLICATION_JSON);
  11. headers.add( "accessToken",setAESDncode( "zhuzi", "hemingzhu"));
  12. request.setAttribute( "tokan",setAESDncode( "zhuzi", "hemingzhu"));
  13. Map<String, Object> requestMap = Maps.newHashMap();
  14. requestMap.put( "id", "123456");
  15. requestMap.put( "name", "xiao ming");
  16. HttpEntity<String> requestEntity = new HttpEntity<String>( null, headers);
  17. ResponseEntity<String> res = restTemplate.exchange(url , HttpMethod.GET , requestEntity , String.class);
  18. return res.getBody();
  19. }
  20. //简单的访问可以不加密
  21. @GetMapping( "zuul/encrypt")
  22. @ResponseBody
  23. public static String setAESDncode(String encodeRules,String content){
  24. try {
  25. //1.构造密钥生成器,指定为AES算法,不区分大小写
  26. KeyGenerator keygen=KeyGenerator.getInstance( "AES");
  27. //2.根据ecnodeRules规则初始化密钥生成器
  28. //生成一个128位的随机源,根据传入的字节数组
  29. keygen.init( 128, new SecureRandom(encodeRules.getBytes()));
  30. //3.产生原始对称密钥
  31. SecretKey original_key=keygen.generateKey();
  32. //4.获得原始对称密钥的字节数组
  33. byte [] raw=original_key.getEncoded();
  34. //5.根据字节数组生成AES密钥
  35. SecretKey key= new SecretKeySpec(raw, "AES");
  36. //6.根据指定算法AES自成密码器
  37. Cipher cipher=Cipher.getInstance( "AES");
  38. //7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
  39. cipher.init(Cipher.ENCRYPT_MODE, key);
  40. //8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
  41. byte [] byte_encode=content.getBytes( "utf-8");
  42. //9.根据密码器的初始化方式--加密:将数据加密
  43. byte [] byte_AES=cipher.doFinal(byte_encode);
  44. //10.将加密后的数据转换为字符串
  45. //这里用Base64Encoder中会找不到包
  46. //解决办法:
  47. //在项目的Build path中先移除JRE System Library,再添加库JRE System Library,重新编译后就一切正常了。
  48. String AES_encode= new String( new BASE64Encoder().encode(byte_AES));
  49. //11.将字符串返回
  50. return AES_encode;
  51. } catch (NoSuchAlgorithmException e) {
  52. e.printStackTrace();
  53. } catch (UnsupportedEncodingException e) {
  54. e.printStackTrace();
  55. } catch (Exception e) {
  56. e.printStackTrace();
  57. }
  58. //如果有错就返加nulll
  59. return null;
  60. }
  61. }

这样差不多就好了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值