1. 程式人生 > 程式設計 >基於Spring Cloud Zookeeper實現服務註冊與發現

基於Spring Cloud Zookeeper實現服務註冊與發現

服務註冊

1.新增Spring Cloud Zookeeper依賴:

<dependencies>
	<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>
	<dependency>
		<groupId>org.apache.zookeeper</groupId>
		<artifactId>zookeeper</artifactId>
		<version>3.6.2</version>
		<exclusions>
			<exclusion>
				<groupId>org.slf4j</groupId>
				<artifactId>slf4j-log4j12</artifactId>
			</exclusion>
		</exclusions>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
</dependencies>

2.在服務配置檔案中新增zookeeper配置:

spring:
 cloud:
  zookeeper:
   connect-string: localhost:2181 #zookeeper地址

3.啟動zookeeper伺服器和服務(我這邊是啟動了兩個服務,分別是provider和consumer),然後在zookeeper客戶端中可以檢視已經註冊到zookeeper中的服務:

基於Spring Cloud Zookeeper實現服務註冊與發現

服務發現

1.建立controller

消費者controller:

package com.buhe.zk.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class ZkConsumerController {
  private static final String SERVICE_NAME = "provider";
  private static final String SERVICE_PATH = "/zk/provider";

  @Autowired
  private RestTemplate restTemplate;

  @Autowired
  private DiscoveryClient discoveryClient;

  /**
   * 呼叫提供者服務
   * @return
   */
  @GetMapping("/zk/consumer")
  public String zkConsumer(){
    return "我吃了" + restTemplate.getForObject("http://" + SERVICE_NAME + SERVICE_PATH,String.class);
  }

  /**
   * 獲取提供者服務URL
   * @return
   */
  @GetMapping("/zk/url")
  public String serviceUrl() {
    List<ServiceInstance> list = discoveryClient.getInstances(SERVICE_NAME);
    if (list != null && list.size() > 0 ) {
      return list.get(0).getUri().toString() + SERVICE_PATH;
    }
    return null;
  }

}

要使用RestTemplate別忘了加配置:

@Bean
@LoadBalanced
public RestTemplate restTemplate(){
	return new RestTemplate();
}

提供者controller:

package com.buhe.zk.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ZkProviderController {

  @GetMapping("/zk/provider")
  public String zkProvider(){
    return "10個蘋果";
  }
}

2.服務呼叫

基於Spring Cloud Zookeeper實現服務註冊與發現

以上就是基於Spring Cloud Zookeeper實現服務註冊與發現的詳細內容,更多關於Spring Cloud Zookeeper服務註冊與發現的資料請關注我們其它相關文章!