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作为资源配置中心