微服务间调用Retrofit在Spring Cloud Alibaba中的使用
作者:MacroZheng 发布时间:2022-09-29 23:13:42
前置知识
在微服务项目中,如果我们想实现服务间调用,一般会选择Feign。之前介绍过一款HTTP客户端工具Retrofit
,配合SpringBoot非常好用!其实Retrofit
不仅支持普通的HTTP调用,还能支持微服务间的调用,负载均衡和熔断限流都能实现。今天我们来介绍下Retrofit
在Spring Cloud Alibaba下的使用,希望对大家有所帮助!
SpringBoot实战电商项目mall(50k+star)地址:
https://github.com/macrozheng/mall
本文主要介绍Retrofit在Spring Cloud Alibaba下的使用,需要用到Nacos和Sentinel,对这些技术不太熟悉的朋友可以先参考下之前的文章。
Spring Cloud Alibaba:Nacos 作为注册中心和配置中心使用
Spring Cloud Alibaba:Sentinel实现熔断与限流
还在用HttpUtil?试试这款优雅的HTTP客户端工具吧,跟SpringBoot绝配!
搭建
在使用之前我们需要先搭建Nacos和Sentinel,再准备一个被调用的服务,使用之前的nacos-user-service
即可。
首先从官网下载Nacos,这里下载的是nacos-server-1.3.0.zip
文件,
下载地址:https://github.com/alibaba/nacos/releases
解压安装包到指定目录,直接运行bin
目录下的startup.cmd
,运行成功后访问Nacos,账号密码均为nacos
,访问地址:http://localhost:8848/nacos
接下来从官网下载Sentinel,这里下载的是sentinel-dashboard-1.6.3.jar
文件,
下载地址:https://github.com/alibaba/Sentinel/releases
下载完成后输入如下命令运行Sentinel控制台;
java -jar sentinel-dashboard-1.6.3.jar
Sentinel控制台默认运行在8080
端口上,登录账号密码均为sentinel
,通过如下地址可以进行访问:http://localhost:8080
接下来启动nacos-user-service
服务,该服务中包含了对User对象的CRUD操作接口,启动成功后它将会在Nacos中注册。
/**
* Created by macro on 2019/8/29.
*/
@RestController
@RequestMapping("/user")
public class UserController {
private Logger LOGGER = LoggerFactory.getLogger(this.getClass());
@Autowired
private UserService userService;
@PostMapping("/create")
public CommonResult create(@RequestBody User user) {
userService.create(user);
return new CommonResult("操作成功", 200);
}
@GetMapping("/{id}")
public CommonResult<User> getUser(@PathVariable Long id) {
User user = userService.getUser(id);
LOGGER.info("根据id获取用户信息,用户名称为:{}",user.getUsername());
return new CommonResult<>(user);
}
@GetMapping("/getUserByIds")
public CommonResult<List<User>> getUserByIds(@RequestParam List<Long> ids) {
List<User> userList= userService.getUserByIds(ids);
LOGGER.info("根据ids获取用户信息,用户列表为:{}",userList);
return new CommonResult<>(userList);
}
@GetMapping("/getByUsername")
public CommonResult<User> getByUsername(@RequestParam String username) {
User user = userService.getByUsername(username);
return new CommonResult<>(user);
}
@PostMapping("/update")
public CommonResult update(@RequestBody User user) {
userService.update(user);
return new CommonResult("操作成功", 200);
}
@PostMapping("/delete/{id}")
public CommonResult delete(@PathVariable Long id) {
userService.delete(id);
return new CommonResult("操作成功", 200);
}
}
使用
接下来我们来介绍下Retrofit的基本使用,包括服务间调用、服务限流和熔断降级。
集成与配置
首先在pom.xml
中添加Nacos、Sentinel和Retrofit相关依赖;
<dependencies>
<!--Nacos注册中心依赖-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--Sentinel依赖-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!--Retrofit依赖-->
<dependency>
<groupId>com.github.lianjiatech</groupId>
<artifactId>retrofit-spring-boot-starter</artifactId>
<version>2.2.18</version>
</dependency>
</dependencies>
然后在application.yml
中对Nacos、Sentinel和Retrofit进行配置,Retrofit配置下日志和开启熔断降级即可;
server:
port: 8402
spring:
application:
name: nacos-retrofit-service
cloud:
nacos:
discovery:
server-addr: localhost:8848 #配置Nacos地址
sentinel:
transport:
dashboard: localhost:8080 #配置sentinel dashboard地址
port: 8719
retrofit:
log:
# 启用日志打印
enable: true
# 日志打印 *
logging-interceptor: com.github.lianjiatech.retrofit.spring.boot.interceptor.DefaultLoggingInterceptor
# 全局日志打印级别
global-log-level: info
# 全局日志打印策略
global-log-strategy: body
# 熔断降级配置
degrade:
# 是否启用熔断降级
enable: true
# 熔断降级实现方式
degrade-type: sentinel
# 熔断资源名称解析器
resource-name-parser: com.github.lianjiatech.retrofit.spring.boot.degrade.DefaultResourceNameParser
再添加一个Retrofit的Java配置,配置好选择服务实例的Bean即可。
/**
* Retrofit相关配置
* Created by macro on 2022/1/26.
*/
@Configuration
public class RetrofitConfig {
@Bean
@Autowired
public ServiceInstanceChooser serviceInstanceChooser(LoadBalancerClient loadBalancerClient) {
return new SpringCloudServiceInstanceChooser(loadBalancerClient);
}
}
服务间调用
使用Retrofit实现微服务间调用非常简单,直接使用@RetrofitClient
注解,通过设置serviceId
为需要调用服务的ID即可;
/**
* 定义Http接口,用于调用远程的User服务
* Created by macro on 2019/9/5.
*/
@RetrofitClient(serviceId = "nacos-user-service", fallback = UserFallbackService.class)
public interface UserService {
@POST("/user/create")
CommonResult create(@Body User user);
@GET("/user/{id}")
CommonResult<User> getUser(@Path("id") Long id);
@GET("/user/getByUsername")
CommonResult<User> getByUsername(@Query("username") String username);
@POST("/user/update")
CommonResult update(@Body User user);
@POST("/user/delete/{id}")
CommonResult delete(@Path("id") Long id);
}
我们可以启动2个nacos-user-service
服务和1个nacos-retrofit-service
服务,此时Nacos注册中心显示如下;
然后通过Swagger进行测试,调用下获取用户详情的接口,发现可以成功返回远程数据,访问地址:http://localhost:8402/swagger-ui/
查看nacos-retrofit-service
服务打印的日志,两个实例的请求调用交替打印,我们可以发现Retrofit通过配置serviceId
即可实现微服务间调用和负载均衡。
服务限流
Retrofit的限流功能基本依赖Sentinel,和直接使用Sentinel并无区别,我们创建一个测试类RateLimitController
来试下它的限流功能;
/**
* 限流功能
* Created by macro on 2019/11/7.
*/
@Api(tags = "RateLimitController",description = "限流功能")
@RestController
@RequestMapping("/rateLimit")
public class RateLimitController {
@ApiOperation("按资源名称限流,需要指定限流处理逻辑")
@GetMapping("/byResource")
@SentinelResource(value = "byResource",blockHandler = "handleException")
public CommonResult byResource() {
return new CommonResult("按资源名称限流", 200);
}
@ApiOperation("按URL限流,有默认的限流处理逻辑")
@GetMapping("/byUrl")
@SentinelResource(value = "byUrl",blockHandler = "handleException")
public CommonResult byUrl() {
return new CommonResult("按url限流", 200);
}
@ApiOperation("自定义通用的限流处理逻辑")
@GetMapping("/customBlockHandler")
@SentinelResource(value = "customBlockHandler", blockHandler = "handleException",blockHandlerClass = CustomBlockHandler.class)
public CommonResult blockHandler() {
return new CommonResult("限流成功", 200);
}
public CommonResult handleException(BlockException exception){
return new CommonResult(exception.getClass().getCanonicalName(),200);
}
}
接下来在Sentinel控制台创建一个根据资源名称
进行限流的规则;
之后我们以较快速度访问该接口时,就会触发限流,返回如下信息。
熔断降级
Retrofit的熔断降级功能也基本依赖于Sentinel,我们创建一个测试类CircleBreakerController
来试下它的熔断降级功能;
/**
* 熔断降级
* Created by macro on 2019/11/7.
*/
@Api(tags = "CircleBreakerController",description = "熔断降级")
@RestController
@RequestMapping("/breaker")
public class CircleBreakerController {
private Logger LOGGER = LoggerFactory.getLogger(CircleBreakerController.class);
@Autowired
private UserService userService;
@ApiOperation("熔断降级")
@RequestMapping(value = "/fallback/{id}",method = RequestMethod.GET)
@SentinelResource(value = "fallback",fallback = "handleFallback")
public CommonResult fallback(@PathVariable Long id) {
return userService.getUser(id);
}
@ApiOperation("忽略异常进行熔断降级")
@RequestMapping(value = "/fallbackException/{id}",method = RequestMethod.GET)
@SentinelResource(value = "fallbackException",fallback = "handleFallback2", exceptionsToIgnore = {NullPointerException.class})
public CommonResult fallbackException(@PathVariable Long id) {
if (id == 1) {
throw new IndexOutOfBoundsException();
} else if (id == 2) {
throw new NullPointerException();
}
return userService.getUser(id);
}
public CommonResult handleFallback(Long id) {
User defaultUser = new User(-1L, "defaultUser", "123456");
return new CommonResult<>(defaultUser,"服务降级返回",200);
}
public CommonResult handleFallback2(@PathVariable Long id, Throwable e) {
LOGGER.error("handleFallback2 id:{},throwable class:{}", id, e.getClass());
User defaultUser = new User(-2L, "defaultUser2", "123456");
return new CommonResult<>(defaultUser,"服务降级返回",200);
}
}
由于我们并没有在nacos-user-service
中定义id为4
的用户,调用过程中会产生异常,所以访问如下接口会返回服务降级结果,返回我们默认的用户信息。
来源:https://juejin.cn/post/7064742963015843870


猜你喜欢
- 一、Java 8 基本 Base64 基本的加
- 模块调用之后,记录模块的相关日志,看似简单,其实暗藏玄机。1.简述模块日志的实现方式大致有三种:AOP + 自定义注解实现输出指定格式日志
- 本文实例为大家分享了Android登录邮箱自动补全功能的实现方法,供大家参考,具体内容如下效果:实现原理:1、继承重写简单控件AutoCom
- 1、回顾一下大家有没有注意到,目前讲到的所有 controller 中的方法接收到请求之后,都是有返回值的,返回值主要有 2 种类型:1、
- 今天遇到pom中添加dependency时相关的jar会自动下载,但是左边的External Libraries中一直获取不到添加的jar问
- 本文实例为大家分享了MapReduce实现决策树算法的具体代码,供大家参考,具体内容如下首先,基于C45决策树算法实现对应的Mapper算子
- 使用Scroller实现绚丽的ListView左右滑动删除Item效果这里来给大家带来使用Scroller的小例子,同时也能用来帮助初步解除
- springboot http转https一、安全证书的生成可以使用jdk自带的证书生成工具,jdk自带一个叫keytool的证书管理工具,
- 为避免繁琐的注册登陆,很多平台和网站都会实现三方登陆的功能,增强用户的粘性。这篇文章主要介绍了java实现微信扫码登录第三方网站功能(原理和
- =====最大线程数====linux 系统中单个进程的最大线程数有其最大的限制 PTHREAD_THREADS_MAX这个限制可以在 /u
- 开发一款App,总会遇到各种各样的需求和业务,这时候选择一个简单好用的轮子,就可以事半功倍前言 Intent intent =
- WebView 网页滚动截屏,可对整个网页进行截屏而不是仅当前屏幕哦! 注意若Web页面存在position:fixed; 的话得在调用前设
- 本文就是会将数组里面的单词进行倒序排列 例如 how old are you -> you are old how示例程序输出结果:t
- 实践过程效果代码public partial class Frm_Libretto : Form{ public
- 前言:平时在实际工作中很少用到这个,虽然都是一些比较基础的东西,但一旦遇到了,又不知所云。刚好最近接触了一些相关这方面的项目,所以也算是对
- 一、项目概述之前有不少粉丝私信我说,能不能用Android原生的语言开发一款在手机上运行的游戏呢?说实话,使用java语言直接开发游戏这个需
- 本文实例讲述了java实现的RSA加密算法。分享给大家供大家参考,具体如下:一、什么是非对称加密1、加密的密钥与加密的密钥不相同,这样的加密
- 在使用IDEA写代码的时候,打开tabs都挤在一行,当打开页面过多的时候,前面的页面无法直观看到,非常不方便。通过简单设置就可以实现tabs
- 一、树概念及结构1.1 树的概念树是一种非线性的数据结构,它是由n(n>=0)个有限结点组成一个具有层次关系的集合。把它叫做树是因 为
- 前言使用基于TCP 协议的双向通信时,网络中的两个应用程序之间必须首先建立一个连接,这两个程序通过一个双向的通信连接实现数据的交换,这个连接