5分钟了解FeignClient的使用
介绍
Feign是一个声明式的伪Http客户端,只需要创建一个接口并注解。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。
使用
下面的代码主要是为了让大家理解使用。
先定义一个注册在Eureka上的Server,application.name是HelloServer。
@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class HelloServerApplication {
/**
* 定义一个地址
*/
@RequestMapping("/")
public String hello() {
return "Hello World: Im server" ;
}
public static void main(String[] args) {
SpringApplication.run(HelloServerApplication.class, args);
}
}
定义一个Client,通过Feign去使用。
@SpringBootApplication
@EnableDiscoveryClient
@RestController
@EnableFeignClients
public class HelloClientApplication {
@Autowired
HelloClient client;
@RequestMapping("/")
public String hello() {
// FeignClient注解的接口自己不需要实现,可以直接的访问HelloServerApplication里定义的的地址
return client.hello();
}
public static void main(String[] args) {
SpringApplication.run(HelloClientApplication.class, args);
}
/**
* 定义接口关联HelloServer服务
*/
@FeignClient("HelloServer")
interface HelloClient {
@RequestMapping(value = "/", method = GET)
String hello();
}
}
