Spring Cloud Alibaba Sidecar 多语言微服务异构

Spring Cloud Alibaba Sidecar 介绍

Spring Cloud Alibaba 2.1.1版本后增加了spring-cloud-alibaba-sidecar模块作为一个代理的服务来间接性的让其他语言可以使用spring cloud alibaba等相关组件。通过与网关来进行路由的映射,从而可以做到服务的获取,然后可以使用Ribbon间接性调用。

Sidecar原理

如上图,Spring Cloud应用请求sidercar然后转发给其他语言的模块,优势是对于异构服务代码零侵入,不需要直接根据nacos或其他注册中心api注册等

使用入门

构建其他语言接口服务

  • 基于go写个简单的服务接口
1
http://127.0.0.1:8089/sidecar
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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依赖
1
2
3
4
5
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sidecar</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
  • 配置application.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
1
2
3
4
5
6
7
8
9
server:
port: 8087
spring:
cloud:
nacos:
discovery:
server-addr: localhost:8848
application:
name: nacos-consumer
  • consumer逻辑
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@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应用
1
curl http://localhost:8087/test   
  • 输出go-provider应用
1
hello spring cloud alibaba sidecar

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2021 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :