• spring cloud 使用Feign调用服务


    在上一篇hello world的基础上,改造Consumer,使用更加便捷,易于理解的Feign来调用服务

    Feign是一个声明式Web Service客户端。

    使用Feign能让编写Web Service客户端更加简单, 它的使用方法是定义一个接口,然后在上面添加注解,同时也支持JAX-RS标准的注解。

    Feign也支持可拔插式的编码器和解码器。

    Spring Cloud对Feign进行了封装,使其支持了Spring MVC标准注解和HttpMessageConverters。

    Feign可以与Eureka和Ribbon组合使用以支持负载均衡。

    pom.xml添加Feign支持

     <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
                <version>2.1.3.RELEASE</version>
     </dependency>

    编写接口MessageRemote

    @FeignClient(name = "PROVIDER")   //注册中心里的服务名称
    public interface MessageRemote {
    
        @RequestMapping(value = "/provider/hello")    //服务中的路径
        Map hello();
    }

    Conroller

    @RestController
    @RequestMapping("/message")
    public class MessageController {
    
        @Autowired
        RestTemplate restTemplate;
    
        @Autowired
        MessageRemote messageRemote;
    
    
        @RequestMapping("/hello")
        public Map hello(){
          return  restTemplate.getForObject("http://PROVIDER/provider/hello", HashMap.class);
        }
    
        @RequestMapping("/remote/hello")
        public Map remoteHello(){
    
            return messageRemote.hello();
        }
    
    }

    浏览器访问:localhost:8080/message/remote/hello

     完成

  • 相关阅读:
    spring基础
    hibernate基础
    struts2基础
    javaEE(17)_邮件原理与JavaMail开发
    javase(14)_java基础增强
    javase(13)_网络编程
    javase(12)_集合框架_Queue
    C++:memset ,memcpy 和strcpy 的根本区别!
    16位的二进制数,每4位为一个数,写函数求他们的和
    态度!!!
  • 原文地址:https://www.cnblogs.com/yhood/p/11571666.html
Copyright © 2020-2023  润新知