SpringCloud--consul的使用方式

由于Eureka 早前一个月 宣布不再维护,目前微服务已经转为以consul作为注册和发现。其中有部分坑 一下一一介绍

docker容器中的consul

本地使用docker的图形化kitematic进行安装并运行consul
这里写图片描述
注意端口暴露为: 8500

示例

注册方

配置文件

其中增加健康检测地址。注意:加了健康检测地址 一定要controller中声明这个地址,否则consul 会认为这是一个无效节点。

server:
  port: 9999
spring:
  cloud:
    consul:
      host: localhost
      #  Consul监听端口8500
      port: 8500
      enabled: true
      discovery:
        # 配置服务注册到Consul上
        register: true
        # 配置服务健康检测地址  供Consul 调用
        health-check-path: /hello
        # consul 健康检测频率
        health-check-interval: 15s
        # 配置注册到consul 服务的id
        instance-id: ${spring.application.name}:${server.port}
        enabled: true
        service-name: ${spring.application.name}
  application:
    name: send

示例注册方

Controller的声明


@RestController
class SendController {

    private val log: Logger = LoggerFactory.getLogger(SendController::class.java)

    @GetMapping("/success")
    fun getMessage(): String {
        return "成功"
    }

    @GetMapping("/hello")
    fun hello(): String {
        return "OK"
    }
}

启动类开启注解

@SpringBootApplication
// 开启consul的注解
@EnableDiscoveryClient 
class SendApplication

fun main(args: Array<String>) {
    runApplication<SendApplication>(*args)
}

发现方

配置文件

同样这里增加了健康检测

server:
  port: 10000
spring:
  cloud:
    consul:
      host: localhost
      #  Consul监听端口8500
      port: 8500
      enabled: true
      discovery:
        # 配置服务注册到Consul上
        register: true
        # 配置服务健康检测地址  供Consul 调用
        health-check-path: /hello
        # consul 健康检测频率
        health-check-interval: 15s
        # 配置注册到consul 服务的id
        instance-id: ${spring.application.name}:${server.port}
        enabled: true
        service-name: ${spring.application.name}
  application:
    name: get

feign 接口声明

注意: 要使用@RequestMapping进行声明接口,如果是post请求需要进行增加method = [RequestMethod.POST]形式来进行区别。 并且@RequestMapping要对应于你的接口映射地址

@FeignClient(name = "send")
@RequestMapping("/")
interface Feign {

    @RequestMapping("/success")
    fun getMessage(): String



}

Feign声明

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = ["com.example.get.feign"])
class GetApplication

fun main(args: Array<String>) {
    runApplication<GetApplication>(*args)
}

进行消费

@RestController
class TestController {

    private val log: Logger = LoggerFactory.getLogger(TestController::class.java)

    @Autowired
    private lateinit var feign: Feign

    @GetMapping("/test")
    fun test(): String {
        return feign.getMessage()
    }

    @GetMapping("/hello")
    fun hello(): String {
        return "OK"
    }

}

拓展

Feign 建议独立建一个模块,进行引用 。 引用的模块需要开启Feign的包扫描@EnableFeignClients(basePackages = ["com.example.get.feign"])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值