springcloud-eureka集群-整合feign框架

Feign是一种声明式、模板化的HTTP客户端。在Spring Cloud中使用Feign, 我们可以做到使用HTTP请求远程服务时能与调用本地方法一样的编码体验,开发者完全感知不到这是远程方法,更感知不到这是个HTTP请求。

1、在之前的项目中对服务调用者加入feign依赖

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-feign</artifactId>
</dependency>

2、修改项目启动类,增加@EnableFeignClients注解

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class EurekaInvocationApplication {
   public static void main(String[] args) {
      SpringApplication.run(EurekaInvocationApplication.class, args);
   }
}

3、编写服务调用接口 @FeignClient(value = "eureka-service") 为服务提供者的实例名

@FeignClient(value = "eureka-service")
public interface IService {

    /**
     * spring的注解翻译器,会把@GetMapping()翻译给feign框架
     * 在feign整合到springcloud后就要用spring的注解,原feign的注解就不能使用了
     * 这里的@PathVariable(value = "id")一定要带上value,否则会报错
     * @return
     */
    @GetMapping(value = "/getUser/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    String getUser(@PathVariable(value = "id") Integer id);

}

4、编写Controller接口,将feign接口注入到Controller

@Autowired
private IService iService;

/**
 * feign 调用服务提供者接口
 * @param id
 * @return
 */
@GetMapping(value = "/getUserFeign/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String getUserFeign(@PathVariable(value = "id") Integer id) {
    return iService.getUser(id);
}

猜你喜欢

转载自blog.csdn.net/Keith003/article/details/82217161