集成openfeign
1、引入依赖,记得版本一致【可以优先引入dependencyManagement】,然后引入openfeign和loadbalancer
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2020.0.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!--openfeign和loadbalancer是配套使用的,需要一块引入-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-loadbalancer</artifactId>
</dependency>
2、将服务注册到nacos或者eureka等注册中心
3、启动类添加注解@EnableFeignClients
@SpringBootApplication(scanBasePackages = {"com.walker"})
@MapperScan("com.walker.infrastructure.mapper")
@EnableFeignClients //添加该注解
public class FunctionLearnApplication {
public static void main(String[] args) {
SpringApplication.run(FunctionLearnApplication.class, args);
}
}
4、新增FeignService服务类,写上注解@FeignClient,@Service/@Component注册容器
@FeignClient("boring-school") //被调用的服务名,和注册中心的保持一致
@Service
public interface TestFeignService {
//将被调用服务的接口方法复制过来,补全调用方法路径
@GetMapping("/boring/test/test1")
R test();
}
//被调用服务接口的代码
@GetMapping("test1")
public R test(){
return R.success("hello weclome to cloud");
}
5、测试
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
//1、注入FeignService
@Autowired
private TestFeignService testFeignService;
@GetMapping("/test")
public void test(){
//2、调用方法
R test = testFeignService.test();
log.info("openfeign返回结果:{}",test);
}
}
//返回结果:
//2021-10-18 11:06:28.478 INFO 1992 --- [io-10024-exec-1] c.w.interfaces.client.UserController : openfeign返回结果:R(code=200, data=hello weclome to cloud, msg=操作成功)</pre>
超时控制
最新的openfeign整合的loadbalancer,而不是ribbon,ribbon的话默认1s会超时,这里需要去了解一下
遇到问题
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalancer?
缺少loadbalancer依赖,将其引入即可,因为在高版本入springcloud 2020.0.2中的openfeign是结合loadbalancer进行负载均衡的
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-loadbalancer</artifactId>
</dependency>