原
SpringlCoud的zuul 网关的使用
1.先搭建eurekaServer
《1》创建一个springboot项目,application.yml中加入一下配置:
-
#端口号
-
server:
-
port:
9002
-
-
#eureka的name
-
spring:
-
application:
-
name: EurekaServer2
-
-
#eureak:搭建eureka集群
-
eureka:
-
instance:
-
hostname: peer2
-
client:
-
register-with-eureka:
false
-
fetch-registry:
false
-
serviceUrl:
-
# 服务的地址
-
defaultZone: http:
//localhost:9002/eureka/
《2》.引入的pom
-
<dependency>
-
<groupId>org.springframework.boot
</groupId>
-
<artifactId>spring-boot-starter-web
</artifactId>
-
</dependency>
-
<dependency>
-
<groupId>org.springframework.cloud
</groupId>
-
<artifactId>spring-cloud-starter-netflix-eureka-server
</artifactId>
-
</dependency>
-
-
<dependency>
-
<groupId>org.springframework.boot
</groupId>
-
<artifactId>spring-boot-starter-test
</artifactId>
-
<scope>test
</scope>
-
</dependency>
《3》添加注解
-
@SpringBootApplication
-
@EnableEurekaServer
-
public
class EurekaApplication {
-
-
public static void main(String[] args) {
-
SpringApplication.run(EurekaApplication.class, args);
-
}
-
}
《4》.eureks已经搭建完成,我们可以访问 http://localhost:9002 就ok了,出现下面的页面就好了
2.搭建一个普通的springboot项目一个接口
-
@RestController
-
public
class ZuulTestController {
-
-
@GetMapping("zuul/c")
-
@ResponseBody
-
public String getZuul(){
-
return
"aaa";
-
}
-
-
}
3.搭建zuul服务
《1》application.yml的配置
-
server:
-
port: 9001
-
-
spring:
-
application:
-
name: zuul
-
zuul:
-
routes:
-
api
-a:
-
path: /ribbon/**
-
serviceId: service-ribbon
-
api-b:
-
path: /feign/**
-
serviceId: service-feign
-
api-c:
-
path: /zuulService/**
-
serviceId: demo1
#注册到eureka的name
-
-
eureka:
-
client:
-
service-url:
-
defaultZone: http://localhost:9002/eureka/
-
instance:
-
prefer-ip-address:
true
-
-
-
ribbon:
-
ReadTimeout: 3000
-
ConnectTimeout: 3000
-
eager-load:
-
enabled:
false
-
-
zuul:
-
host:
-
connect-timeout-millis: 10000
-
socket-timeout-millis: 10000
-
-
hystrix:
-
command:
-
default:
-
execution:
-
isolation:
-
thread:
-
timeout-in-milliseconds: 10000
-
-
《2》添加注解
-
@EnableEurekaClient
-
@EnableZuulProxy
-
@SpringBootApplication
-
public
class ZuulApplication {
-
-
public static void main(String[] args) {
-
SpringApplication.run(ZuulApplication.class, args);
-
}
-
}
《3》pom
-
<dependency>
-
<groupId>org.springframework.boot
</groupId>
-
<artifactId>spring-boot-starter-web
</artifactId>
-
</dependency>
-
<dependency>
-
<groupId>org.springframework.cloud
</groupId>
-
<artifactId>spring-cloud-starter-netflix-zuul
</artifactId>
-
</dependency>
-
-
<dependency>
-
<groupId>org.springframework.boot
</groupId>
-
<artifactId>spring-boot-starter-test
</artifactId>
-
<scope>test
</scope>
-
</dependency>
-
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka -->
-
<dependency>
-
<groupId>org.springframework.cloud
</groupId>
-
<artifactId>spring-cloud-starter-eureka
</artifactId>
-
<version>1.4.5.RELEASE
</version>
-
</dependency>
《4》额外的前置拦截《不做拦截可以不写》
-
import com.netflix.zuul.ZuulFilter;
-
import com.netflix.zuul.context.RequestContext;
-
import org.slf4j.Logger;
-
import org.slf4j.LoggerFactory;
-
import org.springframework.stereotype.Component;
-
import org.springframework.util.StringUtils;
-
import sun.misc.BASE64Decoder;
-
-
import javax.crypto.Cipher;
-
import javax.crypto.KeyGenerator;
-
import javax.crypto.SecretKey;
-
import javax.crypto.spec.SecretKeySpec;
-
import javax.servlet.http.HttpServletRequest;
-
import java.io.BufferedReader;
-
import java.io.IOException;
-
import java.security.SecureRandom;
-
import java.util.Objects;
-
-
@Component
-
public
class RequestFilter extends ZuulFilter {
-
-
private
static Logger log = LoggerFactory.getLogger(RequestFilter.class);
-
-
@Override
-
public String filterType() {
-
//前置过滤器
-
return
"pre";
-
}
-
-
@Override
-
public int filterOrder() {
-
//优先级,数字越大,优先级越低
-
return
0;
-
}
-
-
@Override
-
public boolean shouldFilter() {
-
//是否执行该过滤器,true代表需要过滤
-
return
true;
-
}
-
-
@Override
-
public Object run() {
-
RequestContext ctx = RequestContext.getCurrentContext();
-
-
log.info(
""+ctx);
-
-
HttpServletRequest request = ctx.getRequest();
-
-
log.info(
"send {} request to {}", request.getMethod(), request.getRequestURL().toString());
-
-
//获取传来的参数accessToken
-
Object accessToken = request.getParameter(
"accessToken");
-
-
-
try {
-
BufferedReader br = request.getReader();
-
}
catch (IOException e) {
-
e.printStackTrace();
-
}
-
-
String header = request.getHeader(
"accessToken");
-
-
log.info(
"aaaa="+header);
-
-
-
if(!StringUtils.isEmpty(header)) {
-
String token = AESDncode(
"yy",header);
-
if(token.equals(
"xxx")){
-
return
null;
-
}
-
}
-
log.warn(
"access token is empty");
-
//过滤该请求,不往下级服务去转发请求,到此结束
-
ctx.setSendZuulResponse(
false);
-
ctx.setResponseStatusCode(
401);
-
ctx.setResponseBody(
"{\"result\":\"accessToken为空!\"}");
-
ctx.getResponse().setContentType(
"text/html;charset=UTF-8");
-
return
null;
-
// //如果有token,则进行路由转发
-
// log.info("access token ok");
-
// //这里return的值没有意义,zuul框架没有使用该返回值
-
// return null;
-
}
-
-
public String AESDncode(String encodeRules,String content){
-
try {
-
//1.构造密钥生成器,指定为AES算法,不区分大小写
-
KeyGenerator keygen=KeyGenerator.getInstance(
"AES");
-
//2.根据ecnodeRules规则初始化密钥生成器
-
//生成一个128位的随机源,根据传入的字节数组
-
keygen.init(
128,
new SecureRandom(encodeRules.getBytes()));
-
//3.产生原始对称密钥
-
SecretKey original_key=keygen.generateKey();
-
//4.获得原始对称密钥的字节数组
-
byte [] raw=original_key.getEncoded();
-
//5.根据字节数组生成AES密钥
-
SecretKey key=
new SecretKeySpec(raw,
"AES");
-
//6.根据指定算法AES自成密码器
-
Cipher cipher=Cipher.getInstance(
"AES");
-
//7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二个参数为使用的KEY
-
cipher.init(Cipher.DECRYPT_MODE, key);
-
//8.将加密并编码后的内容解码成字节数组
-
byte [] byte_content=
new BASE64Decoder().decodeBuffer(content);
-
/*
-
* 解密
-
*/
-
byte [] byte_decode=cipher.doFinal(byte_content);
-
String AES_decode=
new String(byte_decode,
"utf-8");
-
return AES_decode;
-
}
catch (Exception e) {
-
e.printStackTrace();
-
}
-
-
//如果有错就返加nulll
-
return
null;
-
}
-
-
-
}
4.写一个对外暴露的controller通过resttemple访问
-
@RestController
-
public
class ZuulTestController {
-
-
@Autowired
-
private RestTemplate restTemplate;
-
-
@GetMapping(
"zuul/test/resourte")
-
@ResponseBody
-
public String getZuulResult(HttpServletRequest request){
-
String url =
"http://localhost:9001/zuulService/zuul/c";
-
-
HttpHeaders headers =
new HttpHeaders();
-
headers.setContentType(MediaType.APPLICATION_JSON);
-
-
headers.add(
"accessToken",setAESDncode(
"zhuzi",
"hemingzhu"));
-
-
request.setAttribute(
"tokan",setAESDncode(
"zhuzi",
"hemingzhu"));
-
-
Map<String, Object> requestMap = Maps.newHashMap();
-
requestMap.put(
"id",
"123456");
-
requestMap.put(
"name",
"xiao ming");
-
-
HttpEntity<String> requestEntity =
new HttpEntity<String>(
null, headers);
-
-
ResponseEntity<String> res = restTemplate.exchange(url , HttpMethod.GET , requestEntity , String.class);
-
-
return res.getBody();
-
}
-
-
-
//简单的访问可以不加密
-
@GetMapping(
"zuul/encrypt")
-
@ResponseBody
-
public static String setAESDncode(String encodeRules,String content){
-
try {
-
//1.构造密钥生成器,指定为AES算法,不区分大小写
-
KeyGenerator keygen=KeyGenerator.getInstance(
"AES");
-
//2.根据ecnodeRules规则初始化密钥生成器
-
//生成一个128位的随机源,根据传入的字节数组
-
keygen.init(
128,
new SecureRandom(encodeRules.getBytes()));
-
//3.产生原始对称密钥
-
SecretKey original_key=keygen.generateKey();
-
//4.获得原始对称密钥的字节数组
-
byte [] raw=original_key.getEncoded();
-
//5.根据字节数组生成AES密钥
-
SecretKey key=
new SecretKeySpec(raw,
"AES");
-
//6.根据指定算法AES自成密码器
-
Cipher cipher=Cipher.getInstance(
"AES");
-
//7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
-
cipher.init(Cipher.ENCRYPT_MODE, key);
-
//8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
-
byte [] byte_encode=content.getBytes(
"utf-8");
-
//9.根据密码器的初始化方式--加密:将数据加密
-
byte [] byte_AES=cipher.doFinal(byte_encode);
-
//10.将加密后的数据转换为字符串
-
//这里用Base64Encoder中会找不到包
-
//解决办法:
-
//在项目的Build path中先移除JRE System Library,再添加库JRE System Library,重新编译后就一切正常了。
-
String AES_encode=
new String(
new BASE64Encoder().encode(byte_AES));
-
//11.将字符串返回
-
return AES_encode;
-
}
catch (NoSuchAlgorithmException e) {
-
e.printStackTrace();
-
}
catch (UnsupportedEncodingException e) {
-
e.printStackTrace();
-
}
catch (Exception e) {
-
e.printStackTrace();
-
}
-
-
//如果有错就返加nulll
-
return
null;
-
-
}
-
-
}
这样差不多就好了