天天看點

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了

繼續閱讀