网站开发深圳,武城网站建设费用,网站扒下来了怎么做,珠海市官网网站建设品牌在微服务项目中#xff0c;如果我们想实现服务间调用#xff0c;一般会选择Feign。之前介绍过一款HTTP客户端工具Retrofit#xff0c;配合SpringBoot非常好用#xff01;其实Retrofit不仅支持普通的HTTP调用#xff0c;还能支持微服务间的调用#xff0c;负载均衡和熔断限… 在微服务项目中如果我们想实现服务间调用一般会选择Feign。之前介绍过一款HTTP客户端工具Retrofit配合SpringBoot非常好用其实Retrofit不仅支持普通的HTTP调用还能支持微服务间的调用负载均衡和熔断限流都能实现。今天我们来介绍下Retrofit在Spring Cloud Alibaba下的使用希望对大家有所帮助搭建 在使用之前我们需要先搭建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.jarSentinel控制台默认运行在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());Autowiredprivate UserService userService;PostMapping(/create)public CommonResult create(RequestBody User user) {userService.create(user);return new CommonResult(操作成功, 200);}GetMapping(/{id})public CommonResultUser getUser(PathVariable Long id) {User user userService.getUser(id);LOGGER.info(根据id获取用户信息用户名称为{},user.getUsername());return new CommonResult(user);}GetMapping(/getUserByIds)public CommonResultListUser getUserByIds(RequestParam ListLong ids) {ListUser userList userService.getUserByIds(ids);LOGGER.info(根据ids获取用户信息用户列表为{},userList);return new CommonResult(userList);}GetMapping(/getByUsername)public CommonResultUser 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注册中心依赖--dependencygroupIdcom.alibaba.cloud/groupIdartifactIdspring-cloud-starter-alibaba-nacos-discovery/artifactId/dependency!--Sentinel依赖--dependencygroupIdcom.alibaba.cloud/groupIdartifactIdspring-cloud-starter-alibaba-sentinel/artifactId/dependency!--Retrofit依赖--dependencygroupIdcom.github.lianjiatech/groupIdartifactIdretrofit-spring-boot-starter/artifactIdversion2.2.18/version/dependency/dependencies然后在application.yml中对Nacos、Sentinel和Retrofit进行配置Retrofit配置下日志和开启熔断降级即可server:port: 8402
spring:application:name: nacos-retrofit-servicecloud: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 {BeanAutowiredpublic 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})CommonResultUser getUser(Path(id) Long id);GET(/user/getByUsername)CommonResultUser 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);Autowiredprivate 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的用户调用过程中会产生异常所以访问如下接口会返回服务降级结果返回我们默认的用户信息。总结 Retrofit给了我们除Feign和Dubbo之外的第三种微服务间调用选择使用起来还是非常方便的。记得之前在使用Feign的过程中实现方的Controller经常要抽出一个接口来方便调用方来实现调用接口实现方和调用方的耦合度很高。如果当时使用的是Retrofit的话这种情况会大大改善。总的来说Retrofit给我们提供了更加优雅的HTTP调用方式不仅是在单体应用中在微服务应用中也一样参考资料 官方文档https://github.com/LianjiaTech/retrofit-spring-boot-starter项目源码地址 https://github.com/macrozheng/springcloud-learning往期推荐Spring Cloud OpenFeign夺命连环9问这谁受得了2022-02-18 玩转Nacos参数配置多图勿点2022-02-21 【万字长文】Spring Cloud Alibaba 开箱即用2022-02-16 求点赞、在看、分享三连