赞
踩
SpringBoot 2.0增加了zookeeper作为注册中心,使用Feign API 的方式演示使用zookeeper作为注册中心,spring-boot-zookeeper 同样内置实现了服务发现,负载均衡等
下面是使用示例
- @EnableFeignClients(clients = HelloApi.class)
- @EnableDiscoveryClient
- @SpringBootApplication
- public class SystemApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(SystemApplication.class, args);
- }
-
- }
zookeeper配置
- #zookeeper注册中心配置
- #Connection string to the Zookeeper cluster
- spring.cloud.zookeeper.connectString=localhost:2181
- #Is Zookeeper enabled
- spring.cloud.zookeeper.enabled=true
定义Feign API
- @FeignClient(value = "spring-boot-zookeeper-demo", path = "api/hello")
- public interface HelloApi {
-
- @RequestMapping(value = "/{name}/getUniqueId")
- public String getUniqueId(@PathVariable("name") String name);
-
- @RequestMapping(value = "/getValue")
- public String getValue(@RequestParam(value = "id") int id);
- }
服务提供者
- /**
- * 服务端-API
- */
- @RestController
- @RequestMapping("/api/hello")
- public class HelloServerController implements HelloApi {
-
- @RequestMapping(value = "/{name}/getUniqueId")
- public String getUniqueId(@PathVariable("name") String name) {
- System.out.println("SERVER--->>>>"+name);
- return "hello world->"+name+" "+new Random().nextDouble();
- }
-
- @RequestMapping(value = "/getValue")
- public String getValue(@RequestParam(value = "id") int id) {
- return "ok:"+new Random().nextDouble();
- }
- }

服务消费者示例
- /**
- * 客户端测试
- */
- @RestController()
- public class HelloClientController {
- @Autowired
- HelloApi helloApi;
-
- @RequestMapping(value="/test/feign")
- public Object test(){
- return helloApi.getUniqueId("zhangsan");
- }
- }
详细了解可以下载源码: https://github.com/kevinLuan/spring-boot-zookeeper-demo.git
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。