Feign抽取、OkHttp连接池
1 Feign抽取
1.1 分析
我们发现,如果每一个feign都有相关的针对单表的操作,那么每一个都写一个样的代码是不合理的而且是麻烦的,那么我们可以参考抽取controller一样的方式去抽取feign ,我们不搞那么复杂,因为feign只是接口声明,
子类继承接口即可。
如图,就是 每一个业务接口 继承 定义了抽取了通用的方法的接口 ,然后每一个业务接口如果是基本的CRUD,都不用进行声明了。直接调用即可。
1.2 代码实现抽取
创建核心feign接口
代码如下:
package com.mingye.core.feign; import com.mingye.common.dto.PageRequestDto; import com.mingye.common.vo.PageResultVo; import com.mingye.common.vo.ResultVo; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import java.io.Serializable; import java.util.List; /** * @version 1.0 * @description 标题 * @package com.mingye.core.feign */ public interface CoreFeign<T> { @DeleteMapping("/del/{id}") ResultVo deleteById(@PathVariable(name = "id") Serializable id); /** * 添加记录 * * @param record * @return */ @PostMapping("/save") ResultVo<T> save(@RequestBody T record); //更新数据 @PutMapping ResultVo updateByPrimaryKey(@RequestBody T record); @GetMapping("/{id}") ResultVo<T> findById(@PathVariable(name = "id") Serializable id) ; @GetMapping ResultVo<List<T>> findAll() ; /** * 根据等号条进行查询调用 * @param record * @return */ @PostMapping("/listCondition") ResultVo<List<T>> findByRecord(@RequestBody T record); /** * 通用条件分页查询 * * @param pageRequestDto * @return */ @PostMapping(value = "/list") PageResultVo<T> findByPage(@RequestBody PageRequestDto pageRequestDto) ; }
添加依赖:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <scope>provided</scope> </dependency> </dependencies>
1.3 使用
给工程的pom文件添加core feign的依赖
修改Feign接口
再测试也是一样的效果,这样就不用重复编写了,
但是要注意的是:请求路径不能和父接口(coreFeign)中的一样。
2 使用OkHttp
在使用默认的feign的时候,feign底层实际上是使用restTemplete 而restTemplate底层又使用到了httpclient,默认使用java自带的httpUrlConnection。我们是可以使用okhttp ,默认的feign调用httpUrlConnection每次都会创建一个链接对象。效率较低。所以使用okhttp来替换,它可以使用连接池。调用效率较高。
在工程中的pom.xml中添加依赖
<dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-okhttp</artifactId> </dependency>
在需要用到feign的微服务中配置如下即可
feign: client: config: default: # default指定的是所有的 被调用方 都设置为该配置超时时间,可以设置为某一个微服务对应的服务名 connectTimeout: 15000 # 链接超时时间 readTimeout: 15000 # 读取的超时时间 loggerLevel: HEADERS #日志级别 okhttp: enabled: true httpclient: enabled: false