zoukankan      html  css  js  c++  java
  • 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,实现了服务调用。

  • 相关阅读:
    背包问题--动态规划
    day03_13 多分支if语句及作业
    day03_12 缩进介绍
    day03_11 if语句实现猜年龄01
    day03_10 注释及简单的用户输入输出
    day03_09 编码部分历史及文件编码简介
    day03_07 变量的重新赋值01
    day03_06 变量详解
    day03_05 Python程序文件执行和与其他编程语言对比
    day03_04 文件后缀及系统环境变量
  • 原文地址:https://www.cnblogs.com/heqiyoujing/p/9239908.html
Copyright © 2011-2022 走看看