天天看點

springcloud學習筆記三:springcloud consul

consul在springcloud作為服務注冊,服務發現的作用,consul服務不需要我們用代碼實作,可以去官網上下載下傳,安裝即可使用

下載下傳位址為:https://www.consul.io/downloads.html

我使用的window版本的consul,使用指令consul agent -dev ,啟動consul server,

1、服務注冊

1、pom添加consul依賴

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

2、啟動程式添加@EnableDiscoveryClient注解

@SpringBootApplication
@EnableDiscoveryClient
public class SpringCloudStuApplication {
   public static void main(String[] args) {
      SpringApplication.run(SpringCloudStuApplication.class, args);
   }
}      

3、配置application.yml檔案

spring:
   application:
      name: yc_consul
   cloud:
      consul:
         host: localhost
         port: 8500
         discovery:
           register: true
           healthCheckPath: /test/hello
           healthCheckInterval: 10s      

 其中healthCheckPath,healthCheckInterval是作為健康檢測的,這個就是每10s去請求/test/hello這個服務

@RestController
@RequestMapping("/test")
public class ZuulTestController {

    @RequestMapping("/hello")
    public String sayHello(){
        System.out.println("-------------------health------check---------------");
        return "hello";
    }      
}

consul預設的健康檢測服務是/health

4、consul作為資源配置中心