除了Ribbon+RestTemplate的方式以外,还有一种基于netflix Feign的机制,简单来讲就是,开发人员定义一个接口,并指定一些描述信息,然后Feign会自动生成一个动态代理,来通过RestTemplate调用服务接口,其本质是对Ribbon+RestTemplate的一个封装。了解springcloud架构可以加求求:三五三六二四七二五九,下面看一下简单的用法
首先,加入一个maven的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
然后在启动类中启用Feign
@SpringBootApplication
@EnableFeignClients
public class EurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class, args);
}
...
12345}接下来定义一个客户端接口类
@FeignClient("myservice1")
public interface MyService1Client {
@GetMapping("/service1")
String service1();
}
需要制定是哪个服务的客户端代理,并且将每个方法都映射到指定服务的接口上。
把这个接口注入到代码中并调用接口的方法,动态代理会自动通过RestTemplate来轮序地调用指定服务的接口
@Autowired
MyService1Client myServicde1Client;
@GetMapping("/call2")
public String call2() {
return myServicde1Client.service1();
}
他的效果和使用Ribbon的调用效果是一样的.