微服务学习6——采用Feign进行通信

这些东东的细节都可以看原版文档

1,maven设置:

To include Feign in your project use the starter with group org.springframework.cloud and artifact id spring-cloud-starter-openfeign. See the Spring Cloud Project page for details on setting up your build system with the current Spring Cloud Release Train.

也就是这么设置:

<dependency>

<groupId>org.springframework.cloud </groupId>

<artifactId>spring-cloud-starter-openfeign</artifactId>

</dependency>

2,入口类设置

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

3,使用Feign类

@FeignClient("stores") public interface StoreClient { @RequestMapping(method = RequestMethod.GET, value = "/stores") List<Store> getStores(); @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json") Store update(@PathVariable("storeId") Long storeId, Store store); }

In the @FeignClient annotation the String value ("stores" above) is an arbitrary client name, which is used to create a Ribbon load balancer (see below for details of Ribbon support). You can also specify a URL using the url attribute (absolute value or just a hostname). The name of the bean in the application context is the fully qualified name of the interface. To specify your own alias value you can use the qualifier value of the @FeignClient annotation.

The Ribbon client above will want to discover the physical addresses for the "stores" service. If your application is a Eureka client then it will resolve the service in the Eureka service registry. If you don’t want to use Eureka, you can simply configure a list of servers in your external configuration (see above for example).

大意就是:

@FeignClient后面的"stores"是任意取的,是用来创建Ribbon load balancer,实际上就是要调用的服务,比如这一句:

@FeignClient(name = "product")

这个product对应的是服务名称:

Feign是一个声明式REST客户端(伪RPC)

采用了基于接口的注解

猜你喜欢

转载自blog.csdn.net/qq_22059611/article/details/88019541