添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
注解开启Feign客户端功能
@EnableFeignClients注解后跟@FeignClient注解所在包名,多个包名用大括号及逗号分隔({…,…})
@SpringBootApplication
@EnableFeignClients("com.act.model.feign")
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
创建Feign接口
- 通过@FeignClient注解创建客户端,value指定调用的服务名称,fallback指定调用异常后执行的方法
- @RequestMapping注解,value指定被调用的服务路径,method指定调用类型
@FeignClient(value = "lou-nacos-service-provider", fallback = UserServiceFallback.class)
public interface Test {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
String hello();
@RequestMapping(value = "/hello1", method = RequestMethod.GET)
String hello1(@RequestParam("name") String name);
}
Feign接口使用
- @Autowired注解将Feign接口类注入
- 调用接口类中定义的方法即可
@Controller
@RequestMapping("/test")
public class TestController {
@Autowired
private Test test;
@ResponseBody
@RequestMapping("/hello")
public String hello(){
System.out.println(test.hello());
return test.hello();
}
@ResponseBody
@RequestMapping("/hello1")
public String hello1(@RequestParam("name")String name){
System.out.println(test.hello1(name));
return test.hello1(name);
}
}