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


声明:本文转载自https://my.oschina.net/giegie/blog/3130830,转载目的在于传递更多信息,仅供学习交流之用。如有侵权行为,请联系我,我会及时删除。

Spring Cloud Alibaba Sidecar 介绍

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

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

使用入门

构建其他语言接口服务

  • 基于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)
}

构建 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权限管理系统 欢迎关注

本文发表于2019年11月18日 17:00
(c)注:本文转载自https://my.oschina.net/giegie/blog/3130830,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。如有侵权行为,请联系我们,我们会及时删除.

阅读 3324 讨论 0 喜欢 0

抢先体验

扫码体验
趣味小程序
文字表情生成器

闪念胶囊

你要过得好哇,这样我才能恨你啊,你要是过得不好,我都不知道该恨你还是拥抱你啊。

直抵黄龙府,与诸君痛饮尔。

那时陪伴我的人啊,你们如今在何方。

不出意外的话,我们再也不会见了,祝你前程似锦。

这世界真好,吃野东西也要留出这条命来看看

快捷链接
网站地图
提交友链
Copyright © 2016 - 2021 Cion.
All Rights Reserved.
京ICP备2021004668号-1