首页 > 编程语言 > 详细

spring cloud 使用Feign调用服务

时间:2019-09-23 12:33:14      阅读:83      评论:0      收藏:0      [点我收藏+]

在上一篇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 cloud 使用Feign调用服务

原文:https://www.cnblogs.com/yhood/p/11571666.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!