20th Chapter Springboot + Consul (1)

Source: Internet
Author: User
Tags spring boot actuator

Consul specific installation and Operation View Blog's Consul series.

First, start consul

(1 server+1 client, convenience, client using this machine): View: http://www.cnblogs.com/java-zhao/p/5375132.html

1. Turn on the virtual machine and switch to the node configured in Vagrantfile

    • Vagrant up
    • Vagrant SSH n110

2. Start 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

Description:-client 0 0 0 0-ui--> enables clients to access the server-side consul UI directly through a URL

3. Start Client (local)

    • Consul AGENT-DATA-DIR=/TMP/CONSUL-NODE=CLIENT-MY-BIND=XXX-DC=ZJGDC1

Description: XXX stands for native IP

4. Client Joins server

    • Consul Join 192.168.21.110

Second, the Java part

1, Pom.xml

<!--consul-client -        <Dependency>            <groupId>Com.orbitz.consul</groupId>            <Artifactid>Consul-client</Artifactid>            <version>0.10.0</version>        </Dependency>        <!--Consul Required Packages -        <Dependency>            <groupId>Org.glassfish.jersey.core</groupId>            <Artifactid>Jersey-client</Artifactid>            <version>2.22.2</version>        </Dependency>

Description: There are two Java clients for consul: Consul-client and Consul-api.

Consul-client's github address: https://github.com/OrbitzWorldwide/consul-client

2, Consulservice

 PackageCom.xxx.firstboot.service;Importjava.net.MalformedURLException;ImportJava.net.URI;Importjava.util.List;ImportOrg.springframework.stereotype.Service;Importcom.orbitz.consul.AgentClient;ImportCom.orbitz.consul.Consul;Importcom.orbitz.consul.HealthClient;Importcom.orbitz.consul.KeyValueClient;//import com.orbitz.consul.NotRegisteredException;Importcom.orbitz.consul.StatusClient;Importcom.orbitz.consul.model.health.ServiceHealth; @Service Public classConsulservice {/*** Registration Service * and Health check of the service * ServiceName only * serviceId: no effect found*/     Public voidRegisterservice (String serviceName, String serviceId) {Consul Consul= Consul.builder (). build ();//Establishing consul InstancesAgentclient agentclient = Consul.agentclient ();//Establish Agentclient                Try {            /*** Note that the registration interface: * Need to provide a health check of the service URL, and how often to access the service (here is 3s)*/Agentclient.register (8080, uri.create ("Http://localhost:8080/health"). Tourl (), 3, ServiceName, serviceId, "Dev"); } Catch(malformedurlexception e) {e.printstacktrace (); }//try {//Agentclient.pass (serviceId);//Health Check//} catch (Notregisteredexception e) {//e.printstacktrace ();//        }    }        /*** Discovery of available Services*/     PublicList<servicehealth>Findhealthyservice (String servicename) {Consul Consul=Consul.builder (). build (); Healthclient healthclient= Consul.healthclient ();//access to all healthy services        returnHealthclient.gethealthyserviceinstances (servicename). GetResponse ();//finding nodes in the passing State    }        /*** Storage kv*/     Public voidstorekv (string key, String value) {Consul Consul=Consul.builder (). build (); Keyvalueclient kvclient=consul.keyvalueclient (); Kvclient.putvalue (key, value);//Storage kv    }        /*** Get value based on key*/     Publicstring getkv (String key) {Consul Consul=Consul.builder (). build (); Keyvalueclient kvclient=consul.keyvalueclient (); returnkvclient.getvalueasstring (key). get (); }        /*** Identify the nodes that are consistent (should be all server nodes in the same DC)*/     PublicList<string>findraftpeers () {statusclient statusclient=Consul.builder (). Build (). Statusclient (); returnstatusclient.getpeers (); }        /*** Get leader*/     PublicString Findraftleader () {statusclient statusclient=Consul.builder (). Build (). Statusclient (); returnStatusclient.getleader (); }    }
View Code

Lists the common APIs.

Attention:

    • The service does not need to pass IP when registering
    • The URL and interval of the health check must be given when the service is registered. The URL is a service (to provide the service, you need to use Spring boot actuator, as follows:).

Add directly to the POMX.ML:

         < Dependency >             < groupId >org.springframework.boot</groupId>             <  Artifactid>spring-boot-starter-actuator</artifactid>          </dependency>

After restarting the app, visit Http://localhost:8080/health and get a JSON string with the following result:

{status: ' Up ', DiskSpace:-{status: ' Up ', Total:249769230336,free:182003318784,threshold:10485760},rabbit:-{status: "Up", Version: "3.6.1"},mongo:-{status: ' Up ', Version: ' 3.2.6 '},db:-{status: ' Up ', Mytestdbdatasource:-{status: ' Up ', D Atabase: "MySQL", Hello:1},mytestdb2datasource:-{status: "Up", Database: "MySQL", Hello:1},datasource:-{status: ' Up ', Database: "MySQL", Hello:1}},_links:-{self:-{href: "http://localhost:8080/health"}}}format online

Description:Status

    • Up: The server is OK (as long as there is one component down, the server is down, so I need to start MONGO and RABBITMQ on the server, here I used the two components)
    • Down: Server hangs

3, Consulcontroller

 PackageCom.xxx.firstboot.web;Importjava.util.List;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.web.bind.annotation.PathVariable;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod;ImportOrg.springframework.web.bind.annotation.RestController;ImportCom.orbitz.consul.model.health.ServiceHealth;ImportCom.xxx.firstboot.service.ConsulService;ImportIo.swagger.annotations.Api;Importio.swagger.annotations.ApiOperation; @Api ("Consul related APIs") @RestController @requestmapping ("/consul") Public classConsulcontroller {@AutowiredPrivateConsulservice Consulservice; /******************************* Service Registration and Discovery *******************************/@ApiOperation ("Registration Service") @RequestMapping (value= "/registerservice/{servicename}/{serviceid}", method=requestmethod.post) Public voidRegisterservice (@PathVariable ("ServiceName") String ServiceName, @PathVariable ("Serviceid"String serviceId) {consulservice.registerservice (serviceName, serviceId); } @ApiOperation ("Discovery Services") @RequestMapping (value= "/discoverservice/{servicename}", method=requestmethod.get) PublicList<servicehealth> Discoverservice (@PathVariable ("ServiceName") String serviceName) {returnConsulservice.findhealthyservice (serviceName); }        /*******************************kv*******************************/@ApiOperation ("Store KV") @RequestMapping (value= "/kv/{key}/{value}", method=requestmethod.post) Public voidSTOREKV (@PathVariable ("Key") String key, @PathVariable ("Value"String value) {CONSULSERVICE.STOREKV (key, value); } @ApiOperation ("Get KV") @RequestMapping (value= "/kv/{key}", method=requestmethod.get) PublicString getkv (@PathVariable ("Key") (String key) {returnconsulservice.getkv (key); }    /*******************************server*******************************/@ApiOperation ("Get all server nodes in the same DC") @RequestMapping (value= "/raftpeers", method=requestmethod.get) PublicList<string>findraftpeers () {returnconsulservice.findraftpeers (); } @ApiOperation ("Get Leader") @RequestMapping (value= "/leader", method=requestmethod.get) PublicString leader () {returnConsulservice.findraftleader (); }}
View Code

4, test (through swagger test + through the Consul UI view results)

    • Swagger:http://localhost:8080/swagger-ui.html
    • Consul ui:http://192.168.21.110:8500/ui/

Shows everything the Consul UI has to show. Services, nodes, KV, Datacenter

20th Chapter Springboot + Consul (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.