SpringCloud学习之Feign服务调用
上一节 SpringCloud学习之RestTemplate中介绍了如何利用Spring提供的RestTemplate方法来完成微服务间的调用,本节将在上节的基础上介绍Feign的使用。Feign的使用更为简洁,提供一个接口即可完成对其他微服务接口的调用。
添加依赖
feign的依赖如下
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
更改service-consumer的主启动类
添加@EnableFeignClients
注解,注入Spring容器
package com.rui;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* @author WangRui
* @date 2020/10/20 16:26
*/
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class ServiceConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceConsumerApplication.class,args);
}
}
service-consumer服务中添加UserServiceFeign
@FeignClient(value = "service-provider")
:该注解可以为该方法找到对应的微服务名称
@RequestMapping("/user/selectAll")
:映射对应的微服务的访问url
package com.rui.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author WangRui
* @date 2020/10/21 15:44
*/
@FeignClient(value = "service-provider")
@Component
public interface UserServiceFeign {
@RequestMapping("/user/selectAll")
String selectAll();
}
更改service-consumer的UserService
添加selectAllFeign()
方法用于调用UserServiceFeign
接口
package com.rui.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
/**
* @author WangRui
* @date 2020/10/21 14:29
*/
@Service
public class UserService {
@Autowired
private RestTemplate restTemplate;
@Autowired
private UserServiceFeign userServiceFeign;
public String selectAll(){
return restTemplate.getForObject("http://localhost:8082/user/selectAll",String.class);
}
public String selectAllFeign(){
return userServiceFeign.selectAll();
}
}
更改service-consumer的UserController
提供@RequestMapping("/selectAllFeign")
来使用feign调用微服务接口
package com.rui.controller;
import com.rui.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author WangRui
* @date 2020/10/21 14:32
*/
@RestController
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/selectAll")
public String selectAll(){
return userService.selectAll();
}
@RequestMapping("/selectAllFeign")
public String selectAllFeign(){
return userService.selectAllFeign();
}
}
通过调用http://localhost:8083/user/selectAllFeign
,同样可以实现微服务应用间的调用。