Spring Boot 如何配置Consul作为服务治理的组件

本文详细介绍如何在SpringBoot项目中使用Consul进行服务治理,包括安装配置Consul、添加依赖、配置YAML文件及启动类等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring Boot 如何配置Consul

背景

  • 由于eureka闭源所以很多公司都会选择consul作为服务治理。

本地安装consul

  • mac版本 请参考 – https://blog.youkuaiyun.com/BigBingtang/article/details/83010209
  • win 版本 请参考 – https://blog.youkuaiyun.com/forezp/article/details/70188595

pom依赖

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>com.sun.jersey</groupId>
                    <artifactId>jersey-client</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

启动类

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

    /**
     * 健康检查,给consul服务发现组件调用的 
     *
     * @return
     */
    @GetMapping("/check")
    public String health() {
        return "I'm OK!--risk Server";
    }
}

yml配置信息

  • 本地启动的配置信息
server:
  port: 8085
spring:
  application:
    name: cc-risk
  cloud:
    consul:
      host: 127.0.0.1
      port: 8500
      discovery:
        health-check-path: /check
        health-check-interval: 5s
        prefer-ip-address: true
        instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${server.port}
    config:
      server:
        native:
          search-locations: classpath:/dev

启动consul

  • consul agent -dev

演示

  • 打开consul的页面客服端 – http://127.0.0.1:8500/ui/dc1/services
  • 如下图所示

在这里插入图片描述

  • 如果文章有帮助到你欢迎关注微信公众号《后端学长》 在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值