自 Spring Cloud Alibaba 2.1.1
版本后增加了 spring-cloud-alibaba-sidecar
模块作为作为一个代理的服务来间接性的让 其他语言 可以使用 spring cloud alibaba
等相关组件。通过与网关的来进行路由的映射,从而可以做到服务的获取,然后可以使用Ribbon间接性调用。
如上图, Spring Cloud 应用 请求 sidercar
然后转发给其他语言的模块,优势是对于异构服务代码 零侵入
,不需要直接根据 nacos
或其他注册中心 api 注册等
http://127.0.0.1:8089/sidecar
package main import ( "encoding/json" "fmt" "log" "net/http" ) func main() { http.HandleFunc("/sidecar", sidecar) http.HandleFunc("/heath", health) log.Fatal(http.ListenAndServe(":8089", nil)) } func sidecar(w http.ResponseWriter, r *http.Request) { _, _ = fmt.Fprintf(w, "hello spring cloud alibaba sidecar") } func health(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") actuator := make(map[string]string) actuator["status"] = "UP" _ = json.NewEncoder(w).Encode(actuator) }
sidercar
应用 sidecar
依赖 <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sidecar</artifactId> <version>2.1.1.RELEASE</version> </dependency>
application.yml
server: port: 8088 spring: cloud: nacos: discovery: server-addr: localhost:8848 application: name: go-provider # 配置异构服务 sidecar: ip: localhost port: 8089 health-check-url: http://localhost:8089/health
nacos consumer
应用 application.yml
server: port: 8087 spring: cloud: nacos: discovery: server-addr: localhost:8848 application: name: nacos-consumer
consumer
逻辑 @RestController @EnableDiscoveryClient @SpringBootApplication public class NacosConsumerApplication { public static void main(String[] args) { SpringApplication.run(NacosConsumerApplication.class, args); } @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } @Autowired private RestTemplate restTemplate; @GetMapping("/test") public String test() { return restTemplate.getForObject("http://go-provider/sidecar", String.class); } }
spring cloud consumer 应用
curl http://localhost:8087/test
go-provider
应用 hello spring cloud alibaba sidecar
项目推荐: Spring Cloud 、Spring Security OAuth2的RBAC权限管理系统 欢迎关注