在微服务项目中,如果我们想实现服务间调用,一般会选择Feign。之前介绍过一款HTTP客户端工具Retrofit,配合SpringBoot非常好用!其实Retrofit不仅支持普通的HTTP调用,还能支持微服务间的调用,负载均衡和熔断限流都能实现。今天我们来介绍下Retrofit在SpringCloudAlibaba下的使用,希望对大家有所帮助!前置知识 本文主要介绍Retrofit在SpringCloudAlibaba下的使用,需要用到Nacos和Sentinel,对这些技术不太熟悉的朋友可以先参考下之前的文章。SpringCloudAlibaba:Nacos作为注册中心和配置中心使用SpringCloudAlibaba:Sentinel实现熔断与限流还在用HttpUtil?试试这款优雅的HTTP客户端工具吧,跟SpringBoot绝配!搭建 在使用之前我们需要先搭建Nacos和Sentinel,再准备一个被调用的服务,使用之前的nacosuserservice即可。首先从官网下载Nacos,这里下载的是nacosserver1。3。0。zip文件,下载地址:https:github。comalibabanacosreleases 解压安装包到指定目录,直接运行bin目录下的startup。cmd,运行成功后访问Nacos,账号密码均为nacos,访问地址:http:localhost:8848nacos 接下来从官网下载Sentinel,这里下载的是sentineldashboard1。6。3。jar文件,下载地址:https:github。comalibabaSentinelreleases 下载完成后输入如下命令运行Sentinel控制台;javajarsentineldashboard1。6。3。jarSentinel控制台默认运行在8080端口上,登录账号密码均为sentinel,通过如下地址可以进行访问:http:localhost:8080 接下来启动nacosuserservice服务,该服务中包含了对User对象的CRUD操作接口,启动成功后它将会在Nacos中注册。Createdbymacroon2019829。RestControllerRequestMapping(user)publicclassUserController{privateLoggerLOGGERLoggerFactory。getLogger(this。getClass());AutowiredprivateUserServiceuserService;PostMapping(create)publicCommonResultcreate(RequestBodyUseruser){userService。create(user);returnnewCommonResult(操作成功,200);}GetMapping({id})publicCommonResultUsergetUser(PathVariableLongid){UseruseruserService。getUser(id);LOGGER。info(根据id获取用户信息,用户名称为:{},user。getUsername());returnnewCommonResult(user);}GetMapping(getUserByIds)publicCommonResultListUsergetUserByIds(RequestParamListLongids){ListUseruserListuserService。getUserByIds(ids);LOGGER。info(根据ids获取用户信息,用户列表为:{},userList);returnnewCommonResult(userList);}GetMapping(getByUsername)publicCommonResultUsergetByUsername(RequestParamStringusername){UseruseruserService。getByUsername(username);returnnewCommonResult(user);}PostMapping(update)publicCommonResultupdate(RequestBodyUseruser){userService。update(user);returnnewCommonResult(操作成功,200);}PostMapping(delete{id})publicCommonResultdelete(PathVariableLongid){userService。delete(id);returnnewCommonResult(操作成功,200);}}使用 接下来我们来介绍下Retrofit的基本使用,包括服务间调用、服务限流和熔断降级。集成与配置首先在pom。xml中添加Nacos、Sentinel和Retrofit相关依赖;dependencies!Nacos注册中心依赖dependencygroupIdcom。alibaba。cloudgroupIdspringcloudstarteralibabanacosdiscoveryartifactIddependency!Sentinel依赖dependencygroupIdcom。alibaba。cloudgroupIdspringcloudstarteralibabasentinelartifactIddependency!Retrofit依赖dependencygroupIdcom。github。lianjiatechgroupIdretrofitspringbootstarterartifactIdversion2。2。18versiondependencydependencies然后在application。yml中对Nacos、Sentinel和Retrofit进行配置,Retrofit配置下日志和开启熔断降级即可;server:port:8402spring:application:name:nacosretrofitservicecloud:nacos:discovery:serveraddr:localhost:8848配置Nacos地址sentinel:transport:dashboard:localhost:8080配置sentineldashboard地址port:8719retrofit:log:启用ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a打印enable:trueahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a打印拦截器logginginterceptor:com。github。lianjiatech。retrofit。spring。boot。interceptor。DefaultLoggingInterceptor全局ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a打印级别globalloglevel:info全局ahrefhttps:www。bs178。comrizhitargetblankclassinfotextkey日志a打印策略globallogstrategy:body熔断降级配置degrade:是否启用熔断降级enable:true熔断降级实现方式degradetype:sentinel熔断资源名称解析器resourcenameparser:com。github。lianjiatech。retrofit。spring。boot。degrade。DefaultResourceNameParser再添加一个Retrofit的Java配置,配置好选择服务实例的Bean即可。Retrofit相关配置Createdbymacroon2022126。ConfigurationpublicclassRetrofitConfig{BeanAutowiredpublicServiceInstanceChooserserviceInstanceChooser(LoadBalancerClientloadBalancerClient){returnnewSpringCloudServiceInstanceChooser(loadBalancerClient);}}服务间调用使用Retrofit实现微服务间调用非常简单,直接使用RetrofitClient注解,通过设置serviceId为需要调用服务的ID即可;定义Http接口,用于调用远程的User服务Createdbymacroon201995。RetrofitClient(serviceIdnacosuserservice,fallbackUserFallbackService。class)publicinterfaceUserService{POST(usercreate)CommonResultcreate(BodyUseruser);GET(user{id})CommonResultUsergetUser(Path(id)Longid);GET(usergetByUsername)CommonResultUsergetByUsername(Query(username)Stringusername);POST(userupdate)CommonResultupdate(BodyUseruser);POST(userdelete{id})CommonResultdelete(Path(id)Longid);}我们可以启动2个nacosuserservice服务和1个nacosretrofitservice服务,此时Nacos注册中心显示如下; 然后通过Swagger进行测试,调用下获取用户详情的接口,发现可以成功返回远程数据,访问地址:http:localhost:8402swaggerui 查看nacosretrofitservice服务打印的日志,两个实例的请求调用交替打印,我们可以发现Retrofit通过配置serviceId即可实现微服务间调用和负载均衡。 服务限流Retrofit的限流功能基本依赖Sentinel,和直接使用Sentinel并无区别,我们创建一个测试类RateLimitController来试下它的限流功能;限流功能Createdbymacroon2019117。Api(tagsRateLimitController,description限流功能)RestControllerRequestMapping(rateLimit)publicclassRateLimitController{ApiOperation(按资源名称限流,需要指定限流处理逻辑)GetMapping(byResource)SentinelResource(valuebyResource,blockHandlerhandleException)publicCommonResultbyResource(){returnnewCommonResult(按资源名称限流,200);}ApiOperation(按URL限流,有默认的限流处理逻辑)GetMapping(byUrl)SentinelResource(valuebyUrl,blockHandlerhandleException)publicCommonResultbyUrl(){returnnewCommonResult(按url限流,200);}ApiOperation(自定义通用的限流处理逻辑)GetMapping(customBlockHandler)SentinelResource(valuecustomBlockHandler,blockHandlerhandleException,blockHandlerClassCustomBlockHandler。class)publicCommonResultblockHandler(){returnnewCommonResult(限流成功,200);}publicCommonResulthandleException(BlockExceptionexception){returnnewCommonResult(exception。getClass()。getCanonicalName(),200);}}接下来在Sentinel控制台创建一个根据资源名称进行限流的规则; 之后我们以较快速度访问该接口时,就会触发限流,返回如下信息。 熔断降级Retrofit的熔断降级功能也基本依赖于Sentinel,我们创建一个测试类CircleBreakerController来试下它的熔断降级功能;熔断降级Createdbymacroon2019117。Api(tagsCircleBreakerController,description熔断降级)RestControllerRequestMapping(breaker)publicclassCircleBreakerController{privateLoggerLOGGERLoggerFactory。getLogger(CircleBreakerController。class);AutowiredprivateUserServiceuserService;ApiOperation(熔断降级)RequestMapping(valuefallback{id},methodRequestMethod。GET)SentinelResource(valuefallback,fallbackhandleFallback)publicCommonResultfallback(PathVariableLongid){returnuserService。getUser(id);}ApiOperation(忽略异常进行熔断降级)RequestMapping(valuefallbackException{id},methodRequestMethod。GET)SentinelResource(valuefallbackException,fallbackhandleFallback2,exceptionsToIgnore{NullPointerException。class})publicCommonResultfallbackException(PathVariableLongid){if(id1){thrownewIndexOutOfBoundsException();}elseif(id2){thrownewNullPointerException();}returnuserService。getUser(id);}publicCommonResulthandleFallback(Longid){UserdefaultUsernewUser(1L,defaultUser,123456);returnnewCommonResult(defaultUser,服务降级返回,200);}publicCommonResulthandleFallback2(PathVariableLongid,Throwablee){LOGGER。error(handleFallback2id:{},throwableclass:{},id,e。getClass());UserdefaultUsernewUser(2L,defaultUser2,123456);returnnewCommonResult(defaultUser,服务降级返回,200);}}由于我们并没有在nacosuserservice中定义id为4的用户,调用过程中会产生异常,所以访问如下接口会返回服务降级结果,返回我们默认的用户信息。 总结 Retrofit给了我们除Feign和Dubbo之外的第三种微服务间调用选择,使用起来还是非常方便的。记得之前在使用Feign的过程中,实现方的Controller经常要抽出一个接口来,方便调用方来实现调用,接口实现方和调用方的耦合度很高。如果当时使用的是Retrofit的话,这种情况会大大改善。总的来说,Retrofit给我们提供了更加优雅的HTTP调用方式,不仅是在单体应用中,在微服务应用中也一样!参考资料 官方文档:https:github。comLianjiaTechretrofitspringbootstarter项目源码地址 https:github。commacrozhengspringcloudlearning