天天看点

Spring Cloud 使用Eureka的feign调用

1、导入依赖

<!--引入EurekaClient-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <!--springcloud整合的openFeign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

           

2、配置yml

#配置Eureka
eureka:
  client:
    service-url:
      defaultZone: http://localhost:9000/eureka/,http://localhost:8000/eureka/
  instance:
    prefer-ip-address: true #使用ip地址注册

#配置feign日志的输出
#日志配置  NONE : 不输出日志(高)   BASIC: 适用于生产环境追踪问题
#HEADERS : 在BASIC的基础上,记录请求和响应头信息   FULL : 记录所有
feign:
  client:
    config:
      service-product:  #需要调用的服务名称
        loggerLevel: FULL
logging:
  level:
    cn.itcast.order.feign.ProductFeignClient: debug

           

3、启动类上添加注解

@SpringBootApplication
@EntityScan("cn.itcast.order.entity")
//激活Feign发现服务
@EnableFeignClients
//@EnableDiscoveryClient  发现服务
public class OrderApplication {

	public static void main(String[] args) {
		SpringApplication.run(OrderApplication.class,args);
	}
}
           

4、创建feignClient接口

/**
 * 声明需要调用的微服务名称
 *  @FeignClient
 *      * name : 服务提供者的名称,
 * 			
 * 整个类配置完成后相当于调用了localhost:service-product/product/{id}这个接口
 */
@FeignClient(name="service-product")
public interface ProductFeignClient {

	/**
	 * 配置需要调用的微服务接口,
	 * 	注意:	不能写@GETMapping(),只能写RequestMapping()
	 * 			@PathVariable中的value值必须指定
	 */
	@RequestMapping(value="/product/{id}",method = RequestMethod.GET)
	public Product findById(@PathVariable("id") Long id);
}


           

5、创建普通接口调用feignClient接口中的方法

@RestController
@RequestMapping("/order")
public class OrderController {

	@Autowired
	private ProductFeignClient productFeignClient;


	/**
	 */
	@RequestMapping(value = "/buy/{id}",method = RequestMethod.GET)
	public Product findById(@PathVariable Long id) {
		Product product = null;
		product = productFeignClient.findById(id);
		return product;
	}


}

           

至此order通过eureka发现服务,并调用就ok了

继续阅读