关于java:还在用Feign推荐一款微服务间调用神器跟SpringCloud绝配

3次阅读

共计 7275 个字符,预计需要花费 19 分钟才能阅读完成。

在微服务项目中,如果咱们想实现服务间调用,个别会抉择 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/na…

  • 解压安装包到指定目录,间接运行 bin 目录下的startup.cmd,运行胜利后拜访 Nacos,账号密码均为nacos,拜访地址:http://localhost:8848/nacos

  • 接下来从官网下载 Sentinel,这里下载的是 sentinel-dashboard-1.6.3.jar 文件,下载地址:https://github.com/alibaba/Se…

  • 下载实现后输出如下命令运行 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…

  • 查看 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 的用户,调用过程中会产生异样,所以拜访如下接口会返回服务降级后果,返回咱们默认的用户信息。

总结

Retrofit 给了咱们除 Feign 和 Dubbo 之外的第三种微服务间调用抉择,应用起来还是十分不便的。记得之前在应用 Feign 的过程中,实现方的 Controller 常常要抽出一个接口来,不便调用方来实现调用,接口实现方和调用方的耦合度很高。如果过后应用的是 Retrofit 的话,这种状况会大大改善。总的来说,Retrofit 给咱们提供了更加优雅的 HTTP 调用形式,不仅是在单体利用中,在微服务利用中也一样!

参考资料

官网文档:https://github.com/LianjiaTec…

我的项目源码地址

https://github.com/macrozheng…

正文完
 0