1、首先创建一个feign的模块并配置依赖,如图:
1、引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
2、编写feign接口(AdminFeign)
package com.jjw.admin.feign;
import com.jjw.admin.pojo.AdUser;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
// name:微服务名 path微服务中controller的类的@RequestMapping("/admin")
@FeignClient(name="leadnews-admin",path = "/admin")
public interface AdminFeign extends CoreFeign<AdUser> {
//创建自媒体账户信息
//@PostMapping
//public Result save(@RequestBody AdUser adUser);
/**
* 根据apUserId获取
* @param apUserId
* @return
*/
@GetMapping("/one/{apUserId}")
public AdUser getByApUserId(@PathVariable(name="apUserId") Integer apUserId);
}
CoreFeign的内容(这部分可以不写,写是为了以后更方便的进行增删改查)
package com.jjw.admin.feign;
import com.jjw.result.pojo.PageInfo;
import com.jjw.result.pojo.PageRequestDto;
import com.jjw.result.pojo.Result;
import org.springframework.web.bind.annotation.*;
import java.io.Serializable;
import java.util.List;
public interface CoreFeign<T> {
@DeleteMapping("/{id}")
public Result deleteById(@PathVariable(name = "id") Serializable id) ;
/**
* 添加记录
*
* @param record
* @return
*/
@PostMapping
public Result<T> save(@RequestBody T record) ;
//更新数据
@PutMapping
public Result updateByPrimaryKey(@RequestBody T record) ;
@GetMapping("/{id}")
public Result<T> findById(@PathVariable(name = "id") Serializable id) ;
@GetMapping
public Result<List<T>> findAll() ;
/**
* 根据等号条进行查询调用
* @param record
* @return
*/
@PostMapping("/listCondition")
public Result<List<T>> findByRecord(@RequestBody T record) ;
/**
* 通用条件分页查询
*
* @param pageRequestDto
* @return
*/
@PostMapping(value = "/search")
public Result<PageInfo<T>> findByPage(@RequestBody PageRequestDto<T> pageRequestDto) ;
}
在name为"leadnews-admin"的微服务的controller类中增添feign的实现接口
@GetMapping("/one/{apUserId}")
public AdUser getByApUserId(@PathVariable(name="apUserId") Integer apUserId){
QueryWrapper<AdUser> queryWrapper = new QueryWrapper<AdUser>();
queryWrapper.eq("id",apUserId);
AdUser adUser = adUserService.getOne(queryWrapper);
return adUser;
}
在使用到feign的微服务中先引入feign的模块id,再调用feign接口
AdUser adUser2 = adminFeign.getByApUserId(adUser.getId());
以上已经完毕了,但是默认的feign调用httpUrlConnection每次都会创建一个链接对象。效率较低。所以使用okhttp来替换,它可以使用连接池。调用效率较高。需要引入feign-okhttp依赖
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
另外在需要用到feign的微服务中配置如下即可
feign:
client:
config:
default: # default指定的是所有的 被调用方 都设置为该配置超时时间,可以设置为某一个微服务对应的服务名
connectTimeout: 5000 # 链接超时时间
readTimeout: 5000 # 读取的超时时间
okhttp:
enabled: true
httpclient:
enabled: false