Gateway结合zookeeper动态路由配置说明
1、 基本大致原理
2、gateway服务器操作
2.1.pom引入zookeeper服务发现的相关依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId><artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
2.2. 配置application.properties
#设置Spring Cloud Zookeeper服务注册中心服务器的连接地址
spring.cloud.zookeeper,connect-string=ip+端口
#Spring Cloud Zookeeper服务注册中心的配置属性,用于指定注册服务的根路径
spring.cloud.zookeeper.discovery.root=services
#Gateway将使用服务注册中心中的服务信息来动态路由请求
spring.cloud.gateway.discovery.locator.enabled=true
spring.cloud.gateway.discovery.locator.enabled为 true 后;系统会自动生成默认的id=xservice,uri: lb://xserver,path=/serviceId/**的路由信息
2.3.项目启动类增加@EnableDiscoveryClient启用服务发现客户端功能生效
@SpringBootApplication
@EnableFeignClients
@EnableApolloConfig(value = {"application","route.yaml"})
@EnableDiscoveryClient
public class GatewayBootstrap {
public static void main(String[] args) {
SpringApplication.run(GatewayBootstrap.class,args);
}
}
3、 Server服务结合zookeeper具体操作
3.1 pom引入zookeeper服务发现的相关依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId><artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
3.2 配置application.properties
#设置Spring Cloud Zookeeper服务注册中心服务器的连接地址
spring.cloud.zookeeper.connect-string=
i
p
:
{ip}:
ip:{port}
#设置服务实例id建议使用
application.namespring.cloud.zookeeper.discovery.instance-id=${application.name}
#启动服务发现功能,这里配置了启动类可以不用配置了
spring.cloud.zookeeper.discovery.enabled=true
#将当前服务实例注册到Spring Cloud Zookeeper服务注册中心
spring.cloud.zookeeper.discovery.register=true
#Spring Cloud Zookeeper服务注册中心的配置属性,用于指定注册服务的根路径。
spring.cloud.zookeeper.discovery.root=xxx
4、测试
serverA、serverB注册到zookeeper中,serverA、serverB分别都有如下代码
@RequestMapping("/hello")
@ResponseBody
public String hello(@RequestParam(name = "name", defaultValue = "server") String name) {
return "Hello A **** " + name;
}
@RequestMapping("/hello")
@ResponseBody
public String hello(@RequestParam(name = "name", defaultValue = "server") String name) {
return "Hello B **** " + name;
}
gateway的地址为http://localhost:14000
测试结果如下:
请求serverA接口地址:http://localhost:14000/serverA/hello
请求serverB接口地址:http://localhost:14000/serverB/hello