一、博客背景
上一篇博客中讲解了ribbon的服务调用,而这篇博客就是讲解通过feign来进行服务间调用,同样是调用数据服务来展示数据。其实Feign 是对 Ribbon的封装,使用注解的方式,调用起来更简单
二、新建feign子模块
三、修改pom文件
相比于ribbon服务,使用feign还需在pom中引入feign依赖
<dependencies>
<!--引入eureka-client依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--引入feign依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
四、新建启动类
启动类中需加上@EnableFeignClients
package tp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* @Package: com.tp
* @ClassName: FeignServerApplication
* @Author: tanp
* @Description: ${description}
* @Date: 2020/7/20 16:45
*/
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class FeignServerApplication {
public static void main(String[] args) {
SpringApplication.run(FeignServerApplication.class,args);
}
}
五、新建供外部调用的controller
在controller中注入feign客户端,调用客户端中的获取数据的方法
package tp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @Package: com.tp
* @ClassName: ShowDataController
* @Author: tanp
* @Description: ${description}
* @Date: 2020/7/20 16:57
*/
@RestController
public class ShowDataController {
@Autowired
FeignClientServer feignClientServer;
@RequestMapping("/getdatas")
public List<String> listData() {
List<String> list = feignClientServer.getDatas();
return list;
}
}
六、新建feign客户端
在客户端中使用注解@FeignClient 定义feign客户端 ,注解的value值为你需要调用的数据服务的服务名,然后用@GetMapping注解表明你调用数据服务中的那个方法
package tp;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.List;
/**
* @Package: com.tp
* @ClassName: FeignClientServer
* @Author: tanp
* @Description: ${description}
* @Date: 2020/7/20 16:59
*/
@Service
@FeignClient(value = "DATA-SERVER")
public interface FeignClientServer {
@GetMapping("/datas")
public List<String> getDatas();
}
七、新建yml文件
与ribbon的没有什么区别,配置端口号,服务名,配置注册中心的地址
spring:
application:
name: feign-server
server:
port: 8685
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8689/eureka/
八、启动并访问
启动后,首先可以发现注册中心中已经多了feign的微服务
然后访问http://127.0.0.1:8685/getdatas
从上面的图中可以看到,我们已经成功的调用了两个数据服务的数进行展示,想要更多了解feign调用机制的同学可以自己额外去了解