Sidecar多语言微服务入手
Sidecar组件的作用是支撑其他语言和平台的微服务,向提供或调用其他语言微服务接口。
搭建准备
名词解释
- 微服务提供者
该微服务提供服务接口给其它微服务调用。 - 微服务调用者
该微服务调用其他微服务的服务接口。 - 异语言微服务
指在spring cloud微服务框架下的其他语言微服务。
示例准备
- 在本示例中时,达到效果需要至少四个项目
- 基于Eureka的微服务注册中心:eureka-server
- 基于SpringBoot的微服务提供者:server-provider
- 基于Sidecar的多语言微服务支持:service-sidecar-server
- 基于NodeJS的微服务消费者:node-customer
异语言搭建和部署
- 在对异语言搭建和部署时,只需要
- 基于Sidecar的多语言微服务支持:service-sidecar-server
- 异语言的微服务(例如Ruby,NodeJS):example-service
起步
- 创建,编写和运行eureka-server,作为注册中心,配置跟正常注册中心一样。
- 创建,编写和运行server-provider,作为服务提供者示。例
- 创建,编写和运行service-sidecar-server, example-service, 作为服务调用者示例。
在对异构(多语言)搭建和部署时,要求
- 异语言微服务, Sidecar服务必须部署在同一台主机上。
- 每个异语言微服务都需要一个Sidecar服务一对一配套部署。
异语言微服务调用者调用微服务提供者的服务时,无需知晓对方IP,只需要知晓该微服务在注册中心注册的名字,然后通过Sidecar调用。以下举例。
- 创建并配置(运行在某个端口上),运行Spring Cloud Sidecar项目。
配置yml
server:
port: 8100
sidecar:
port: 8101 # 微服务的端口
health-uri: http://localhost:8060/health.json # 微服务的健康检查URL
- 创建,配置,运行异语言微服务(运行在另一个端口上)。
- 需要响应Sidecar,以及提供健康检查。
检查方式为,提供一个接口(一般为/health,在Sidecar的yml文件中配置约定的路径),返回
{
"status": "UP"
}
示例
server-provider(服务提供者)
在此项目中,服务提供者运行在8001端口。
# application.yml
spring:
application:
name: provider-server-client
server:
port: 8001
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8000/eureka/
instance:
instance-id: ${spring.application.name}:${server.port}
// TestController.java
/**
此处监听了</test>路径的GET请求并返回字符串。
*/
@RestController
@EnableDiscoveryClient
@RequestMapping("/test")
public class TestController {
@GetMapping
public String tets(){
return "这条数据由Spring Boot项目: provider-server-client返回";
}
@GetMapping("/add/{a}/{b}")
public Integer add(@PathVariable Integer a, @PathVariable Integer b){
return new Random().nextInt() + b;
}
}
Sidecar
在本例中,java项目:service-sidecar-server运行在8100端口
# application.yml
spring:
application:
name: demo-sidercar-server # 微服务名
server:
port: 8100 # sidecar运行端口
eureka:
client:
service-url:
defaultZone: http://localhost:8000/eureka/ # 注册中心主机
instance:
prefer-ip-address: true
instance-id: ${spring.application.name}:${server.port}
sidecar:
port: 8101 # 异语言微服务运行端口
health-uri: http://localhost:8101/health # 健康检查url
node-customer(异语言微服务示例)
const express = require('express')
const logger = require('morgan')
const request = require('request')
const app = express()
const port = 8101
app.use(logger('combined'))
//服务健康检查接口
app.get('/health', (req, res) => {
res.json({
status: 'UP'
})
})
//调用其它微服务测试
var options = {
url:'http://localhost:8100/provider-server-client/test' //调用地址
}
app.get('/nodetest', (req, res) => {
request.get(options, function(err, response, body){
res.json({
data: response.body
})
})
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
//....
上述例子中,在同一台主机运行Sidecar服务(端口:8100)和Node语言的微服务(端口:8101)之后,在NodeJS中直接调用Sidecar服务,带上其它微服务名(或者称为ID)
http://localhost:8100/provider-server-client/test
运行结果: