自 Spring Cloud Alibaba 2.1.1
版本後增長了 spring-cloud-alibaba-sidecar
模塊做爲做爲一個代理的服務來間接性的讓其餘語言能夠使用spring cloud alibaba
等相關組件。經過與網關的來進行路由的映射,從而能夠作到服務的獲取,而後能夠使用Ribbon間接性調用。git
如上圖, Spring Cloud 應用 請求 sidercar
而後轉發給其餘語言的模塊,優點是對於異構服務代碼 零侵入
,不須要直接根據 nacos
或其餘註冊中心 api 註冊等spring
http://127.0.0.1:8089/sidecar
json
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權限管理系統 歡迎關注api