第二十章 springboot + consul(1)

来源:http://www.cnblogs.com/java-zhao/archive/2016/05/25/5527779.html
-Advertisement-
Play Games

consul的具體安裝與操作查看博客的consul系列。 一、啟動consul (1個server+1個client,方便起見,client使用本機):查看:http://www.cnblogs.com/java-zhao/p/5375132.html 1、開啟虛擬機-->切換到vagrantFil ...


consul的具體安裝與操作查看博客的consul系列。

一、啟動consul

(1個server+1個client,方便起見,client使用本機):查看:http://www.cnblogs.com/java-zhao/p/5375132.html

1、開啟虛擬機-->切換到vagrantFile中配置的節點

  • vagrant up
  • vagrant ssh n110

2、啟動server(n110)

  • consul agent -server -bootstrap-expect=1  -data-dir=/tmp/consul -node=server-110 -bind=192.168.21.110 -dc=zjgdc1 -client 0.0.0.0 -ui

說明:-client 0 0 0 0 -ui-->使得客戶端可以直接通過url訪問服務端的consul ui

3、啟動client(local)

  • consul agent -data-dir=/tmp/consul -node=client-my -bind=xxx -dc=zjgdc1

說明:xxx代表本機IP

4、client加入server

  • consul join 192.168.21.110

二、java部分

1、pom.xml

        <!-- consul-client -->
        <dependency>
            <groupId>com.orbitz.consul</groupId>
            <artifactId>consul-client</artifactId>
            <version>0.10.0</version>
        </dependency>
        <!-- consul需要的包 -->
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
            <version>2.22.2</version>
        </dependency>

說明:consul的java客戶端有兩個:consul-client和consul-api。

consul-client的github地址:https://github.com/OrbitzWorldwide/consul-client

2、ConsulService

 1 package com.xxx.firstboot.service;
 2 
 3 import java.net.MalformedURLException;
 4 import java.net.URI;
 5 import java.util.List;
 6 
 7 import org.springframework.stereotype.Service;
 8 
 9 import com.orbitz.consul.AgentClient;
10 import com.orbitz.consul.Consul;
11 import com.orbitz.consul.HealthClient;
12 import com.orbitz.consul.KeyValueClient;
13 //import com.orbitz.consul.NotRegisteredException;
14 import com.orbitz.consul.StatusClient;
15 import com.orbitz.consul.model.health.ServiceHealth;
16 
17 @Service
18 public class ConsulService {
19     
20     /**
21      * 註冊服務
22      * 並對服務進行健康檢查
23      * servicename唯一
24      * serviceId:沒發現有什麼作用
25      */
26     public void registerService(String serviceName, String serviceId) {
27         Consul consul = Consul.builder().build();            //建立consul實例
28         AgentClient agentClient = consul.agentClient();        //建立AgentClient
29         
30         try {
31             /**
32              * 註意該註冊介面:
33              * 需要提供一個健康檢查的服務URL,以及每隔多長時間訪問一下該服務(這裡是3s)
34              */
35             agentClient.register(8080, URI.create("http://localhost:8080/health").toURL(), 3, serviceName, serviceId, "dev");
36         } catch (MalformedURLException e) {
37             e.printStackTrace();
38         }
39 //        try {
40 //            agentClient.pass(serviceId);//健康檢查
41 //        } catch (NotRegisteredException e) {
42 //            e.printStackTrace();
43 //        }
44     }
45     
46     /**
47      * 發現可用的服務
48      */
49     public List<ServiceHealth> findHealthyService(String servicename){
50         Consul consul = Consul.builder().build();
51         HealthClient healthClient = consul.healthClient();//獲取所有健康的服務
52         return healthClient.getHealthyServiceInstances(servicename).getResponse();//尋找passing狀態的節點
53     }
54     
55     /**
56      * 存儲KV
57      */
58     public void storeKV(String key, String value){
59         Consul consul = Consul.builder().build();
60         KeyValueClient kvClient = consul.keyValueClient();
61         kvClient.putValue(key, value);//存儲KV
62     }
63     
64     /**
65      * 根據key獲取value
66      */
67     public String getKV(String key){
68         Consul consul = Consul.builder().build();
69         KeyValueClient kvClient = consul.keyValueClient();
70         return kvClient.getValueAsString(key).get();
71     }
72     
73     /**
74      * 找出一致性的節點(應該是同一個DC中的所有server節點)
75      */
76     public List<String> findRaftPeers(){
77         StatusClient statusClient = Consul.builder().build().statusClient();
78         return statusClient.getPeers();
79     }
80     
81     /**
82      * 獲取leader
83      */
84     public String findRaftLeader(){
85         StatusClient statusClient = Consul.builder().build().statusClient();
86         return statusClient.getLeader();
87     }
88     
89 }

列出了常用API。

註意:

  • 服務註冊的時候不需要傳遞IP
  • 服務註冊的時候需要給出health check的url和時間間隔。該url是一個服務(要提供該服務,需要使用spring boot actuator,具體操作如下:)。

直接在pomx.ml中加入:

1         <dependency>
2             <groupId>org.springframework.boot</groupId>
3             <artifactId>spring-boot-starter-actuator</artifactId>
4         </dependency>

此時重啟應用後,訪問http://localhost:8080/health,得到如下結果一個json串:

 1 {
 2 status: "UP",
 3 diskSpace: - {
 4 status: "UP",
 5 total: 249769230336,
 6 free: 182003318784,
 7 threshold: 10485760
 8 },
 9 rabbit: - {
10 status: "UP",
11 version: "3.6.1"
12 },
13 mongo: - {
14 status: "UP",
15 version: "3.2.6"
16 },
17 db: - {
18 status: "UP",
19 myTestDbDataSource: - {
20 status: "UP",
21 database: "MySQL",
22 hello: 1
23 },
24 myTestDb2DataSource: - {
25 status: "UP",
26 database: "MySQL",
27 hello: 1
28 },
29 dataSource: - {
30 status: "UP",
31 database: "MySQL",
32 hello: 1
33 }
34 },
35 _links: - {
36 self: - {
37 href: "http://localhost:8080/health"
38 }
39 }
40 }
41 Format online

說明:status

  • UP:伺服器正常(以上只要有一個組件DOWN,伺服器就處於DOWN,所以我需要啟動伺服器上的mongo和rabbitmq,這裡我之前使用了這兩個組件)
  • DOWN:伺服器掛了

3、ConsulController

 1 package com.xxx.firstboot.web;
 2 
 3 import java.util.List;
 4 
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.web.bind.annotation.PathVariable;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.bind.annotation.RequestMethod;
 9 import org.springframework.web.bind.annotation.RestController;
10 
11 import com.orbitz.consul.model.health.ServiceHealth;
12 import com.xxx.firstboot.service.ConsulService;
13 
14 import io.swagger.annotations.Api;
15 import io.swagger.annotations.ApiOperation;
16 
17 @Api("consul相關API")
18 @RestController
19 @RequestMapping("/consul")
20 public class ConsulController {
21     @Autowired
22     private ConsulService consulService;
23 
24     /*******************************服務註冊與發現*******************************/
25     @ApiOperation("註冊服務")
26     @RequestMapping(value="/registerService/{servicename}/{serviceid}",method=RequestMethod.POST)
27     public void registerService(@PathVariable("servicename") String serviceName, 
28                                 @PathVariable("serviceid") String serviceId) {
29         consulService.registerService(serviceName, serviceId);
30     }
31     
32     @ApiOperation("發現服務")
33     @RequestMapping(value="/discoverService/{servicename}",method=RequestMethod.GET)
34     public List<ServiceHealth> discoverService(@PathVariable("servicename") String serviceName) {
35         return consulService.findHealthyService(serviceName);
36     }
37     
38     /*******************************KV*******************************/
39     @ApiOperation("store KV")
40     @RequestMapping(value="/kv/{key}/{value}",method=RequestMethod.POST)
41     public void storeKV(@PathVariable("key") String key, 
42                         @PathVariable("value") String value) {
43         consulService.storeKV(key, value);
44     }
45     
46     @ApiOperation("get KV")
47     @RequestMapping(value="/kv/{key}",method=RequestMethod.GET)
48     public String getKV(@PathVariable("key") String key) {
49         return consulService.getKV(key);
50     }
51 
52     /*******************************server*******************************/
53     @ApiOperation("獲取同一個DC中的所有server節點")
54     @RequestMapping(value="/raftpeers",method=RequestMethod.GET)
55     public List<String> findRaftPeers() {
56         return consulService.findRaftPeers();
57     }
58     
59     @ApiOperation("獲取leader")
60     @RequestMapping(value="/leader",method=RequestMethod.GET)
61     public String leader() {
62         return consulService.findRaftLeader();
63     }
64 }

4、測試(通過swagger測試+通過consul UI查看結果)

  • swagger:http://localhost:8080/swagger-ui.html
  • consul UI:http://192.168.21.110:8500/ui/

上圖展示了consul UI所展示的所有東西。services、nodes、kv、datacenter


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Day 15 集合框架01 TreeSet02 TreeSet存儲自定義對象03 二叉樹04 實現Comparator方式排序05 TreeSet練習06 泛型概述07 泛型使用08 泛型類09 泛型方法10 靜態方法泛型11 泛型介面12 泛型限定13 泛型限定2 01 TreeSet |--Se ...
  • 出自:http://www.diybl.com/course/3_program/python/20111130/563643.html 模塊名: 小寫字母,單詞之間用_分割 ad_stats.py 包名: 和模塊名一樣 類名: 單詞首字母大寫 AdStats ConfigUtil 全局變數名(類變 ...
  • 目標:tomcat伺服器提供的介面,不能在其他域中訪問的時候,需要增 Access-Control-Allow-Origin:* 直接配置的方法很多,但是我一個沒有成功過,所以只能自己寫攔截器了。 1. 編寫攔截器代碼 新建一個類,實現Filter介面,代碼如下 2. 配置web.xml 3. 刪除 ...
  • 01 關於本書 02 代碼約定 03 關於例子 04 如何聯繫我們 1 核心模塊 11 介紹 111 內建函數和異常 112 操作系統介面模塊 113 類型支持模塊 114 正則表達式 115 語言支持模塊 12 _ _builtin_ _ 模塊 121 使用元組或字典中的參數調用函數 1211 E ...
  • Write a function that takes a string as input and reverse only the vowels of a string. Example 1:Given s = "hello", return "holle". Example 2:Given s ...
  • 想要深入瞭解JVM,就必須瞭解其實現機制。瞭解JVM實現的最好方法便是自己動手編譯JDK。好了,讓我們開始吧! 1. 準備工作 獲取OpenJDK源碼 獲取OpenJDK源碼 本次編譯選擇的是OpenJDK7u,官方源碼包:https://jdk7.java.net/source.html 系統需求 ...
  • Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. Note: Each element i ...
  • 嚴格來講是給在OSC上貢獻過內容的OSC用戶刷積分。 OSC很多操作都需要消耗積分,很多人給OSC貢獻了內容, 但是卻沒有人點贊,所以有些人在OSC混了很多年也沒有積分。 本文中使用到的工具有gifcam 、fiddler 、Wireshark。gifcam 是一個小巧的GIF錄屏軟體,可以把你電腦 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...