Spring Cloud(三):声明式调用

声明式服务调用

    前面在使用spring cloud时,通常都会利用它对RestTemplate的请求拦截来实现对依赖服务的接口调用,RestTemplate实现了对http的请求封装处理,形成了一套模板化的方法。而spring cloud feign在此基础上做了封装,我们只需要创建一个接口用注解的方式配置它,便可完成对服务方的接口绑定。

在pom.xml中添加依赖:

 1 <dependency>
 2             <groupId>org.springframework.boot</groupId>
 3             <artifactId>spring-boot-starter-web</artifactId>
 4         </dependency>
 5 
 6         <dependency>
 7             <groupId>org.springframework.cloud</groupId>
 8             <artifactId>spring-cloud-starter-eureka-server</artifactId>
 9         </dependency>
10         <dependency>
11             <groupId>org.springframework.boot</groupId>
12             <artifactId>spring-boot-starter-test</artifactId>
13             <scope>test</scope>
14         </dependency>
15         <dependency>
16             <groupId>org.springframework.cloud</groupId>
17             <artifactId>spring-cloud-starter-feign</artifactId>
18         </dependency>
19     </dependencies>

创建主类ApplicationFeign:

 1 @EnableFeignClients
 2 @EnableDiscoveryClient
 3 @SpringBootApplication
 4 public class ApplicationFeign {
 5 
 6 
 7     public static void main(String[] args) {
 8         SpringApplication.run(ApplicationFeign.class, args);
 9     }
10 
11 }

定义HelloService接口:

@FeignClient(value = "hello-service")
public interface HelloService {

    @RequestMapping("/hello")
    String hello();

 
}

创建ConsumerController:

 1 @RestController
 2 public class ConsumerController {
 3 
 4     @Autowired
 5     HelloService helloService;
 6 
 7     @RequestMapping(value = "/feign-consumer", method = RequestMethod.GET)
 8     public String helloConsumer() {
 9         return helloService.hello();
10     }
11 
12 }

配置文件:

1 server.port=9001
2 spring.application.name=feign-consumer
3 eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/

访问http://localhost:9001/feign-consumer  :

通过feign,实现了服务调用。

原文地址:https://www.cnblogs.com/heqiyoujing/p/9239908.html