目录
- 待补
Sidecar简介
- 在springcloud的项目中,我们需要允许使用不同语言去实现微服务,但是非java语言是无法接入eureka,hystrix,fegin,ribbon等相关组件。有一种思路就是启动一个代理的微服务,由该代理微服务同非jvm服务交流,并接入eureka等相关组件。Sidecar就是该思路的实现,总结的说就是作为一个代理的服务来间接性的让其他语言可以使用Eureka等相关组件。
- 目前sidecar这个服务必须和非jvm语言的服务在同一台主机上面,也就是说他们之间是localhost访问的,不能是ip访问等等
- 目前觉得sidecar还不是非常适用,如每一个异构的微服务都要对应的建一个sidecar的微服务,十分不合理。
Sidecare 同nodejs示例
1.一个简单的nodejs文件
var http = require('http');
var url = require("url");
var path = require('path');
// 创建server
var server = http.createServer(function(req, res) {
// 获得请求的路径
var pathname = url.parse(req.url).pathname;
res.writeHead(200, { 'Content-Type' : 'application/json; charset=utf-8' });
// 访问http://localhost:8060/,将会返回{"index":"欢迎来到首页"}
if (pathname === '/') {
res.end(JSON.stringify({ "index" : "欢迎来到首页" }));
}
// 访问http://localhost:8060/health,将会返回{"status":"UP"}
else if (pathname === '/health.json') {
res.end(JSON.stringify({ "status" : "UP" }));
}
// 其他情况返回404
else {
res.end("404");
}
});
// 创建监听,并打印日志
server.listen(8060, function() {
console.log('listening on localhost:8060');
});
2.创建sidecar的微服务,添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-sidecar</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
3.入口程序增加@EnableSidecar注解
- @EnableSidecar包含了@EnableCircuitBreaker, @EnableDiscoveryClient, @EnableZuulProxy等注解,所以hystrix的熔断器、Eureka的服务发现、zuul代理,这些该有的部件,都已经开启
@SpringBootApplication
@EnableSidecar
public class SidecarApplication {
public static void main(String[] args) {
SpringApplication.run(SidecarApplication.class, args);
}
}
4.配置文件
- sidecar.port 关联的微服务的端口,即Node.js应用监听的端口
- sidecar.health-uri 是一个用来模拟Spring Boot应用健康指标的接口的uri。它必须返回如下形式的json文档(health-uri-document):{ “status” : “UP” }
spring:
application:
name: microservice-sidecar
server:
port: 8077
eureka:
client:
service-url:
defaultZone: http://user:password123@localhost:8761/eureka
instance:
prefer-ip-address: true
sidecar:
port: 8060
health-uri: http://localhost:8060/health.json
5.最终实现的效果为
当你以http://xxxx:8077/health.json访问时,sidecar接收到该请求会向nodejs发送请求http://localhost:8060/health.json,并将接收到结果返回。