Spring Cloud Alibaba Sidecar introduction

Since Spring Cloud Alibaba 2.1.1, the spring-Cloud-Alibaba-Sidecar module has been added as a proxy service to indirectly enable other languages to use Spring Cloud Alibaba and other related components. Services can be obtained by mapping routes to gateways, and then invoked indirectly using the Ribbon.

As shown above, Spring Cloud applications request SiderCar and then forward it to modules in other languages. The advantage is that there is no intrusion into heterogeneous service code and no need to register directly with NACOS or other registry apis

Introduction to use

Build other language interface services

  • Write a simple service interface based on GO

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)
}Copy the code

buildsidercarapplication

  • increasesidecarRely on
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sidecar</artifactId> < version > 2.1.1. RELEASE < / version > < / dependency >Copy the code
  • configurationapplication.yml
server: port: 8088 spring: cloud: nacos: discovery: server-addr: localhost:8848 application: name: Go - the provider # configuration sidecars heterogeneous service: IP: localhost port: 8089 health - check - url: http://localhost:8089/healthCopy the code

buildnacos consumerapplication

  • application.yml
server:
  port: 8087
spring:
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
  application:
    name: nacos-consumerCopy the code
  • consumerlogic
@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);
    }

}Copy the code

Test using

  • accessSpring Cloud Consumer application
curl http://localhost:8087/test   Copy the code

  • The outputgo-providerapplication
hello spring cloud alibaba sidecarCopy the code

Project recommendation: Spring Cloud, Spring Security OAuth2 RBAC permission management system welcome to pay attention to