Feign调用步骤:
1.配置pom文件中引入Feign
2.启动类加入注解
3.声明需要调用的接口
1.配置pom文件中引入Feign和Consul
<!-- Feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<!-- consul -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
2.启动类加入注解
@SpringBootApplication
@EnableDiscoveryClient//向服务中心注册,为了让其他微服务能调用你
@EnableFeignClients//声明客户端接口(能使用Feign进行调用)
public class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
@Bean //向程序的ioc注入一个bean: restTemplate
@LoadBalanced //表明这个restRemplate开启负载均衡的功能
RestTemplate restTemplate(){
return new RestTemplate();
}
}
3.声明需要调用的接口
/**
* @这个Client由服务提供方提供
* @添加@FeignClient注解是为了调用方的在服务注册机器上找到服务提供方
*/
@FeignClient(value = "service-provider") //@FeignClient,将接口声明为Feign客户端,这里的service-provider对应调用服务的applicaiton.yml文件中spring:application:name即(应用本身的名称也是微服务在注册中心上的名称)
public interface ServiceFeignClient {
@RequestMapping(value = "/hi")
String hi(@RequestParam("id") String id);
}