SpringCloud集成zookeeper&Feign API

本文详细介绍了如何在SpringBoot2.0中整合Zookeeper作为注册中心,通过Feign实现服务调用。包括配置zookeeper连接、定义Feign API、实现服务提供者与消费者的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值