由于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"])