赞
踩
spring cloud技术栈:
对于分布式系统来说,服务注册与发现是一项非常重要的功能。Spring Cloud是一个非常流行的微服务框架,它提供了一些组件来帮助我们实现服务注册与发现的功能。其中,Zookeeper也是一种常用的服务注册与发现工具。
在本文中,我们将介绍如何在Spring Cloud项目中集成Zookeeper,并实现服务注册与发现的功能。
在此之前需要安装windows客户端,下载地址:
https://zookeeper.apache.org/
点击下载,解压到自己想要的位置:
解压后打开apache-zookeeper-3.8.1-bin\conf
复制zoo_sample.cfg,重命名为:zoo_cfg后打开添加以下代码:
dataDir=D:\SoftWare\apache-zookeeper-3.8.1-bin\data
dataLogDir=D:\SoftWare\apache-zookeeper-3.8.1-bin\data\log
admin.enable=true
接着编辑apache-zookeeper-3.8.1-bin\bin\zkServer.cmd添加
“-Dzookeeper.audit.enable=true”
set ZOOMAIN=org.apache.zookeeper.server.quorum.QuorumPeerMain
set ZOO_LOG_FILE=zookeeper-%USERNAME%-server-%COMPUTERNAME%.log
echo on
call %JAVA% "-Dzookeeper.audit.enable=true" "-Dzookeeper.log.dir=%ZOO_LOG_DIR%" "-Dzookeeper.log.file=%ZOO_LOG_FILE%" "-XX:+HeapDumpOnOutOfMemoryError" "-XX:OnOutOfMemoryError=cmd /c taskkill /pid %%%%p /t /f" -cp "%CLASSPATH%" %ZOOMAIN% "%ZOOCFG%" %*
endlocal
首先,我们需要在pom.xml文件中添加如下依赖:
<!-- Spring Cloud Zookeeper -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
</dependency>
这个依赖将为我们提供集成Zookeeper的功能。
接下来,我们需要配置Zookeeper连接信息。在application.properties或application.yml文件中添加如下配置:
spring.cloud.zookeeper.connect-string=localhost:2181
spring.cloud.zookeeper.discovery.register=true
spring.cloud.zookeeper.discovery.prefer-ip-address=true
其中,connect-string表示Zookeeper的地址,这里我们使用本地的Zookeeper;register表示是否启用服务注册功能;prefer-ip-address表示是否使用IP地址注册。
现在,我们可以在需要注册的服务中添加@EnableDiscoveryClient注解,例如:
@SpringBootApplication
@EnableDiscoveryClient
public class MyService {
public static void main(String[] args) {
SpringApplication.run(MyService.class, args);
}
}
这里的@EnableDiscoveryClient注解表示启用服务注册功能。
@GetMapping("/payment/zk")
public CommonResult paymentzk() {
return new CommonResult(200, "端口号:" + serverPort, "ZOOKEEPER");
}
pom、yml、启动类配置与上述一样。
@RestController
@Slf4j
public class OrderZookeeperController {
private static final String URL = "http://cloud-payment-service";
@Resource
private RestTemplate restTemplate;
@GetMapping(value = "/consumer/payment/zk")
public CommonResult<Payment> getPayment() {
return restTemplate.getForObject(URL + "/payment/zk", CommonResult.class);
}
}
URL表示在服务注册中心注册的服务名称,在这里直接使用可以忽略服务提供者的端口和地址。
以上就是使用Spring Cloud集成Zookeeper实现服务注册与发现的示例。通过这个例子,我们可以看到,使用Spring Cloud可以很方便地实现服务注册与发现的功能,并且可以支持多种服务注册与发现工具。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。