1.使用docker部署zookeeper
下载镜像:
docker pull zookeeper:3.5
运行容器:
docker run --privileged=true -d --name zookeeper1 --publish 2182:2181 -d zookeeper:3.5
2.搭建服务提供者
添加maven配置
org.springframework.boot
spring-boot-starter-parent
2.0.7.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-zookeeper-discovery
org.springframework.cloud
spring-cloud-dependencies
Finchley.SR2
pom
import
application.yml文件
spring:
application:
name: HelloWorld
cloud:
zookeeper:
connect-string: 192.168.180.129:2182
discovery:
enabled: true
server:
port: 8081
endpoints:
restart:
enabled: true
logging:
level:
org.apache.zookeeper.ClientCnxn: WARN
在Application类添加注解@EnableDiscoveryClient和@SpringBootApplication
@EnableDiscoveryClient
@SpringBootApplication
public class ServiceZKApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceZKApplication.class, args);
}
}
创建controller,serviceUrl()方法返回结果为已注册成功的服务提供者实例。
@RestController
@RequestMapping("/zookeeper")
public class ZookeeperController {
@Value("${spring.application.name}")
private String instanceName;
private final DiscoveryClient discoveryClient;
@Autowired
public ZookeeperController(DiscoveryClient discoveryClient) {
this.discoveryClient = discoveryClient;
}
@GetMapping
public String hello() {
return "Hello,Zookeeper.";
}
@GetMapping("/services")
public List serviceUrl() {
List list = discoveryClient.getInstances(instanceName);
List services = new ArrayList<>();
if (list != null && list.size() > 0 ) {
list.forEach(serviceInstance -> {
services.add(serviceInstance.getUri().toString());
});
}
return services;
}
}
3.服务消费者
本例采用feign client方式调用服务
maven配置,相比服务提供者,多了一个feign引用
org.springframework.boot
spring-boot-starter-parent
2.0.7.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-zookeeper-discovery
org.springframework.cloud
spring-cloud-starter-feign
1.4.6.RELEASE
org.springframework.cloud
spring-cloud-dependencies
Finchley.SR2
pom
import
application.properties,也可以用yml文件
spring.application.name=service-zookeeper
server.port=8083
management.security.enabled=false
spring.cloud.zookeeper.connect-string=192.168.180.129:2182
feign调用方法
@Configuration
@EnableFeignClients
@EnableDiscoveryClient
public class HelloWorldClient {
@Autowired
private TheClient theClient;
@FeignClient(name = "HelloWorld")
interface TheClient {
@RequestMapping(path = "/zookeeper/services", method = RequestMethod.GET)
@ResponseBody
String HelloWorld();
}
public String HelloWorld() {
return theClient.HelloWorld();
}
}
新建controller调用HelloWorldClient
@RestController
public class HelloWorldController {
@Autowired
private HelloWorldClient helloWorldClient;
@GetMapping("/test1")
public String sayhello() {
return helloWorldClient.HelloWorld();
}
}
将服务提供者和服务消费者分别运行起来
调用消费者接口 http://127.0.0.1:8083/test1
直接调用提供者接口 http://127.0.0.1:8081/zookeeper/services
这两个结果应该是一样的,都返回了服务提供者的实例列表。