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

 完成

猜你喜欢

转载自www.cnblogs.com/yhood/p/11571666.html