您的当前位置:首页正文

SpringCloudFeign简单使用详解

来源:我们爱旅游
SpringCloudFeign简单使⽤详解

概述

在⼀⽂中简单的介绍了在Spring Cloud中如何使⽤EureKa和Ribbon。⽂章中使⽤了RestTemplate去访问其他的restful微服务接⼝。其实在Spring Cloud还可以使⽤Feign来访问其他的restful微服务接⼝。使⽤起来更加的简洁明了。集成Feign

修改⼀下中order service的pom配置,把Fegin引⼊进来即可。

org.springframework.cloud spring-cloud-starter-feign

修改OrderApplication类,删除如下代码:

@Bean

@LoadBalanced

RestTemplate restTemplate() { return new RestTemplate(); }

并加上@EnableFeignClients注解。完整代码如下:

package com.springboot;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.netflix.feign.EnableFeignClients;@EnableDiscoveryClient@EnableFeignClients@SpringBootApplication

public class OrderApplication {

public static void main(String[] args) {

SpringApplication.run(OrderApplication.class, args); }}

新增接⼝UserService,并使⽤@FeignClient注解。

package com.springboot;

import org.springframework.cloud.netflix.feign.FeignClient;import org.springframework.web.bind.annotation.GetMapping;@FeignClient(name=\"user\")public interface UserService { @GetMapping(value=\"/getUser\") String getUser();}

这⾥的@FeignClient(name=\"user\")中的name=user表⽰要访问user这个微服务。由于order这个微服务已经集成了Eureka和Ribbon。那么使⽤@FeignClient(name=\"user\")访问user微服务的时候,已经⾃动⽀持客户端路由了。并且会从注册中⼼中找到user这个微服务。

修改OrderController,注⼊UserService。

package com.springboot;

import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestController

public class OrderController { @Autowired

private UserService userService; @GetMapping(\"/getOrderUser\")

public String getOrderUser() { return userService.getUser(); }}

这样就⽆需使⽤

restTemplate.getForEntity(\"http://user/getUser\

来调⽤user服务中的getUser接⼝了。⽽是直接使⽤userService.getUser()就可以了。访问⼀下。是可以返回I am user list.

以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

因篇幅问题不能全部显示,请点此查看更多更全内容