Spring Cloud
技术栈采用Zuul
作为微服务网关,在整个架构中,Zuul
是所有其他微服务的统一入口,对所有请求进行路由。
<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">
<parent>
<artifactId>tensquare_parentartifactId>
<groupId>com.tensquaregroupId>
<version>1.0.0-SNAPSHOTversion>
parent>
<modelVersion>4.0.0modelVersion>
<artifactId>tensquare_managerartifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-netflix-eureka-clientartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-zuulartifactId>
dependency>
dependencies>
project>
server:
port: 9011
spring:
application:
name: tensquare‐manager #指定服务名
eureka:
instance:
prefer‐ip‐address: true
client:
service-url:
defaultZone: http://127.0.0.1:6868/eureka/
zuul:
routes:
tensquare‐gathering: #活动
path: /gathering/**
serviceId: tensquare‐gathering
tensquare‐article: #文章
path: /article/**
serviceId: tensquare‐article
tensquare‐base: #基础
path: /base/**
serviceId: tensquare‐base
tensquare‐friend: #交友
path: /friend/**
serviceId: tensquare‐friend
tensquare‐qa: #问答
path: /qa/**
serviceId: tensquare‐qa
tensquare‐recruit: #招聘
path: /recruit/**
serviceId: tensquare‐recruit
tensquare‐spit: #吐槽
path: /spit/**
serviceId: tensquare‐spit
tensquare‐user: #用户
path: /user/**
serviceId: tensquare‐user
package com.tensquare.manager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@SpringBootApplication
@EnableZuulProxy
public class ManagerApplication {
public static void main(String[] args) {
SpringApplication.run(ManagerApplication.class, args);
}
}
<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">
<parent>
<artifactId>tensquare_parentartifactId>
<groupId>com.tensquaregroupId>
<version>1.0.0-SNAPSHOTversion>
parent>
<modelVersion>4.0.0modelVersion>
<artifactId>tensquare_webartifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-netflix-eureka-clientartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-zuulartifactId>
dependency>
dependencies>
project>
server:
port: 9012
spring:
application:
name: tensquare‐web #指定服务名
eureka:
instance:
prefer‐ip‐address: true
client:
service-url:
defaultZone: http://127.0.0.1:6868/eureka/
zuul:
routes:
tensquare‐gathering: #活动
path: /gathering/**
serviceId: tensquare‐gathering
tensquare‐article: #文章
path: /article/**
serviceId: tensquare‐article
tensquare‐base: #基础
path: /base/**
serviceId: tensquare‐base
tensquare‐friend: #交友
path: /friend/**
serviceId: tensquare‐friend
tensquare‐qa: #问答
path: /qa/**
serviceId: tensquare‐qa
tensquare‐recruit: #招聘
path: /recruit/**
serviceId: tensquare‐recruit
tensquare‐spit: #吐槽
path: /spit/**
serviceId: tensquare‐spit
tensquare‐user: #用户
path: /user/**
serviceId: tensquare‐user
tensquare‐search: #用户
path: /user/**
serviceId: tensquare‐search
package com.tensquare.web;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@EnableZuulProxy
@SpringBootApplication
public class WebApplication {
public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
}
编写Zuul
过滤器实现Token
转发
package com.tensquare.web.filter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
@Component
public class WebFilter extends ZuulFilter {
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 0;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
System.out.println("zuul过滤器...");
//向header中添加鉴权令牌
RequestContext requestContext = RequestContext.getCurrentContext();
//获取header
HttpServletRequest request = requestContext.getRequest();
String authorization = request.getHeader("Authorization");
if (authorization != null) {
requestContext.addZuulRequestHeader("Authorization", authorization);
}
return null;
}
}
我的另一篇文章有详细介绍Zuul
,文章链接:Zuul网关详解
<dependency>
<groupId>com.tensquaregroupId>
<artifactId>tensquare_commonartifactId>
<version>${tensquare.version}version>
dependency>
配置在application.yml
即可
jwt:
config:
key: imxushuai
配置在ManagerApplication
即可
@Bean
public JwtUtil jwtUtil(){
return new JwtUtil();
}
package com.tensquare.manager.filter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.JwtUtil;
import javax.servlet.http.HttpServletRequest;
@Slf4j
@Component
public class ManagerFilter extends ZuulFilter {
@Autowired
private JwtUtil jwtUtil;
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 0;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
RequestContext requestContext = RequestContext.getCurrentContext();
HttpServletRequest request = requestContext.getRequest();
if (request.getMethod().equals("OPTIONS")) {// 跳过预请求
return null;
}
String url = request.getRequestURL().toString();
if (url.indexOf("/admin/login") > 0) {// 放行登录
log.info("登陆页面: [{}]", url);
return null;
}
String authHeader = request.getHeader("Authorization");//获取头信息
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.substring(7);
Claims claims = jwtUtil.parseJWT(token);
if (claims != null) {
if ("admin".equals(claims.get("roles"))) {
requestContext.addZuulRequestHeader("Authorization", authHeader);
log.info("Token验证通过,头信息 [{}]", authHeader);
return null;
}
}
}
requestContext.setSendZuulResponse(false);//终止运行
requestContext.setResponseStatusCode(401);//http状态码
requestContext.setResponseBody("无权访问");
requestContext.getResponse().setContentType("text/html;charset=UTF‐8");
return null;
}
}
在分布式系统中,由于服务数量巨多,为了方便服务配置文件统一管理,实时更新,所 以需要分布式配置中心组件。在Spring Cloud
中,有分布式配置中心组件spring cloud config
,它支持配置服务放在配置服务的内存中(即本地),也支持放在远程Git仓库 中。在spring cloud config
组件中,分两个角色,一是config server
,二是config client
。
Config Server
是一个可横向扩展、集中式的配置服务器,它用于集中管理应用程序各个环境下的配置,默认使用Git存储配置文件内容,也可以使用SVN存储,或者是本地文件存储。在Git
服务器上创建用于存放配置文件的仓库。创建好后,将所有的配置文件上传至Git
服务器。
<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">
<parent>
<artifactId>tensquare_parentartifactId>
<groupId>com.tensquaregroupId>
<version>1.0.0-SNAPSHOTversion>
parent>
<modelVersion>4.0.0modelVersion>
<artifactId>tensquare_configartifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-config-serverartifactId>
dependency>
dependencies>
project>
spring:
application:
name: tensquare‐config
cloud:
config:
server:
git:
uri: https://github.com/imxushuai/tensquare_config.git
server:
port: 12000
package com.tensquare.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@EnableConfigServer
@SpringBootApplication
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
成功拉取到配置文件!
在需要从配置中心拉取配置的微服务中重复一下操作:
引入Spring Cloud Config
依赖
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-configartifactId>
dependency>
在resources
目录中新增配置文件:bootstrap.yml
spring:
cloud:
config:
# 应用名
name: base
# 环境
profile: dev
# 分支
label: master
# 配置中心地址
uri: http://127.0.0.1:12000
配置完毕后,即可删除配置文件
application.yml
,测试是否能正常启动。
使用Spring Cloud Bus
实现实时更新配置文件,当Git
库配置文件发送变动时,热更新相应微服务的配置文件。
原理参考:点击我
在tensquare_config
中引入依赖
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-busartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-stream-binder-rabbitartifactId>
dependency>
新增后的application.yml
配置文件内容如下:
spring:
application:
name: tensquare‐config
cloud:
config:
server:
git:
uri: https://github.com/imxushuai/tensquare_config.git
rabbitmq:
host: 192.168.136.104
server:
port: 12000
management:
endpoints:
web:
exposure:
include: bus-refresh
在需要从配置中心拉取配置的微服务中重复一下操作:
引入Spring Cloud Bus
依赖
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-busartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-stream-binder-rabbitartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
注意:这里新增的配置需要在Git
服务器中的每个配置文件中加入下面这段配置。
spring:
rabbitmq:
host: 192.168.136.104
这样配置文件热更新的基本上算是完成了,以后在每一次配置文件有更新的时候,我们只需要调用一个接口,就可以完成配置文件的热更新了。
接口:http://127.0.0.1:12000/actuator/bus-refresh
Spring Cloud Bus
更新只会更新框架已有的配置项,而不会更新类似Jwt
等用户自定义的配置项。
需要更新自定义的配置项,需要在要更新配置项的Bean
上使用@RefreshScope
注解,这样就可以完成配置的更新。