1. 程式人生 > >Spring Cloud 中使用zookeeper作為服務註冊中心與配置中心

Spring Cloud 中使用zookeeper作為服務註冊中心與配置中心

前段時間,瞭解了通過spring-cloud-config-server與spring-cloud-eureka-server作為配置中心與註冊中心,同時瞭解到基於zookeeper或consul可以完成同樣的事情,所以必須瞭解一下,這樣有利於實際工作的技術對比與選型。

安裝zookeeper

下載

解壓

tar -xvf zookeeper-3.4.10.tar.gz

啟動zookeeper

cd zookeeper-3.4.10
cd conf
cp zoo_sample.cfg zoo.cfg
cd ../bin
sh zkServer.sh start

使用zookeeper作為服務註冊中心

maven依賴

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
        </dependency>

啟用

package com.garlic.springcloudzookeeperclientapp;

import
org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * zookeeper作為服務註冊中心,應用啟動類 * * @author sam.liu */ @SpringBootApplication @EnableDiscoveryClient public class
SpringCloudZookeeperClientAppApplication {
public static void main(String[] args) { SpringApplication.run(SpringCloudZookeeperClientAppApplication.class, args); } }

application.properties

## 配置應用名稱
spring.application.name=spring-cloud-zookeeper-client-app

## 配置服務埠
server.port=8080

## 關閉安全控制
management.security.enabled=false

## 配置zookeeper地址
spring.cloud.zookeeper.connect-string=localhost:2181

使用DiscoveryClient獲取註冊服務列表

package com.garlic.springcloudzookeeperclientapp.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 提供Rest Api,根據例項名稱獲取註冊服務列表
 *
 * @author sam.liu
 * @create 2017-11-21 20:47
 * @contact 563750241
 * @email [email protected]
 */
@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<String> serviceUrl() {
        List<ServiceInstance> list = discoveryClient.getInstances(instanceName);
        List<String> services = new ArrayList<>();
        if (list != null && list.size() > 0 ) {
            list.forEach(serviceInstance -> {
                services.add(serviceInstance.getUri().toString());
            });
        }
        return services;
    }


}

注:可以啟動不同的例項,此處我啟動了埠80808081兩個例項,然後使用端點可以查詢到所註冊的服務列表

同樣可以通過zookeeper相關命令查詢到說註冊的服務列表

sh zkCli.sh
[services, zookeeper][zk: localhost:2181(CONNECTED) 1] ls /
[services, zookeeper][zk: localhost:2181(CONNECTED) 2] ls /services
[spring-cloud-zookeeper-client-app][zk: localhost:2181(CONNECTED) 3] ls /services/spring-cloud-zookeeper-client-app
[be61af3d-ffc2-4ffc-932c-26bc0f94971c, bcf21ece-e9e1-4a91-b985-8828688370b8][zk: localhost:2181(CONNECTED) 4]

使用zookeeper作為配置中心

使用zkCli建立配置資訊

[zk: localhost:2181(CONNECTED) 27] create /config ""
Created /config
[zk: localhost:2181(CONNECTED) 28] create /config ""
Created /config/garlic
[zk: localhost:2181(CONNECTED) 29] create /config/garlic/name "default"
Created /config/garlic/name
[zk: localhost:2181(CONNECTED) 30] set /config/garlic-dev/name "dev"
Node does not exist: /config/garlic-dev/name
[zk: localhost:2181(CONNECTED) 31] create /config/garlic-dev/name "dev"
Created /config/garlic-dev/name
[zk: localhost:2181(CONNECTED) 32] create /config/garlic-test/name "test"
Created /config/garlic-test/name
[zk: localhost:2181(CONNECTED) 33] create /config/garlic-prod/name "prod"

maven依賴

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zookeeper-config</artifactId>
        </dependency>

bootstrap.properties

## 啟用zookeeper作為配置中心
spring.cloud.zookeeper.config.enabled = true

## 配置根路徑
spring.cloud.zookeeper.config.root = config

## 配置預設上下文
spring.cloud.zookeeper.config.defaultContext = garlic

## 配置profile分隔符
spring.cloud.zookeeper.config.profileSeparator = -

spring.cloud.zookeeper.config.root對應zkCli建立的config目錄,defaultContext對應建立的garlicgarlic-*目錄,根據profile來確定獲取dev還是test或者prod配置

application.properties

## 配置應用名稱
spring.application.name=spring-cloud-zookeeper-config-app

## 配置服務埠
server.port=10000

## 關閉安全控制
management.security.enabled=false

spring.profiles.active=dev

編寫Controller來動態獲取zookeeper配置中心的資料

package com.garlic.springcloudzookeeperconfigapp.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 提供Rest Api,獲取配置在zookeeper中的配置資訊
 *
 * @author sam.liu
 * @create 2017-11-21 16:13
 * @contact 563750241
 * @email [email protected]
 */
@RestController
@RequestMapping("/zookeeper")
@RefreshScope // 必須新增,否則不會自動重新整理name的值
public class ZookeeperController {

    @Autowired
    private Environment environment;

    @Value("${name}")
    private String name;

    @GetMapping
    public String hello() {
        return "Hello, " + name;
    }

    @GetMapping("/env")
    public String test() {
        String name = environment.getProperty("name");
        System.out.println(name);
        return "Hello," + name;
    }

}

啟動配置例項之後,可以通過zkCli修改garlicname的值,然後通過訪問端點來檢視值是否變化

至此,使用zookeeper作為服務註冊中心與配置中心就完成了,我們可以通過使用zookeeper作為配置中心,然後使用zuul作為API閘道器,配置動態路由,為服務提供者,配置資料庫連線相關資訊。