Gateway结合zookeeper动态路由配置说明

		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
在这里插入图片描述

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值