spring cloud使用zookeeper作爲服務註冊中心和配置中心

        現在用spring cloud框架搭建微服務已經是比較流行了,畢竟這個是spring提供給我們的一個框架,可以很好配合spring boot使用,很快就可以搭建出一個微服務來,大大的減少了工作量。
        這裏就談一下,各個微服務之間要怎麼的互相調用。這個就需要一個有服務註冊和發現功能的服務,所有的微服務註冊到這個服務上面,這樣的話,所有的微服務就客戶互相的調用了。
        服務的註冊和發現功能,目前有兩種形式:一種是客戶端發現(eureka),比較流行。另一種是服務端發現(zookeeper或consul)。
        這裏主要談一下使用zookeeper作爲服務註冊中心與配置中心。

一、服務註冊中心

1.安裝zookeeper

       解壓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

2.引入依賴          

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

3.創建微服務,並以zookeeper作爲服務註冊中心。

package com.garlic.springcloudzookeeperclientapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * zookeeper作爲服務註冊中心,應用啓動類
 * @author llsydn
 */
@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 llsydn
 * @create 2018-5-11 20:47
 */
@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]

二、配置中心

1.使用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"

2.使用controller來動態獲取zookeeper配置中心的數據

2.1maven依賴

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

2.2bootstrap.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配置

2.3application.properties

## 配置應用名稱
spring.application.name=spring-cloud-zookeeper-config-app
## 配置服務端口
server.port=10000
## 關閉安全控制
management.security.enabled=false
spring.profiles.active=dev

2.4使用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 llsydn
 * @create 2018-5-11 20:50
 */
@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網關,配置動態路由,爲服務提供者,配置數據庫連接相關信息。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章