SpringCloud 入门笔记(三)Feign声明式HTTP调用

版权声明:本文为博主原创,转载请注明出处! https://blog.csdn.net/greedystar/article/details/88993324

在SpringCloud中,每个微服务即是服务提供者也是服务消费者,各个微服务之间经常需要互相调用。通常,服务会向外部提供一些REST接口,供外部服务调用,Feign就是提供服务间声明式HTTP调用的组件。通过Feign,我们可以使用SpringMVC注解创建访问其他服务接口的HTTP客户端。

本篇以前面构建的 user-ms 和 role-ms 微服务为例,配置Feign组件。

配置Feign组件

在pom.xml中添加如下依赖:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

在启动类添加@EnableFeignClients注解,如下:

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class UserMsApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserMsApplication.class, args);
    }
}

在user-ms中创建一个FeignClient接口,作为Feign客户端,通过SpringMVC注解访问role-ms微服务,如下所示:

@FeignClient(name = "role-ms")
public interface RoleFeignClient {

    @RequestMapping(value = {"/role/list"}, method = RequestMethod.GET)
    Object list();

    @RequestMapping(value = "/role/insert", method = RequestMethod.POST)
    String insert(@RequestBody Role role);

}

在UserController中定义访问role-ms的接口,如下:

@RestController
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleFeignClient roleFeignClient;

    @RequestMapping(value = {"/list", ""}, method = RequestMethod.GET)
    public Object list() {
        List<User> users = userService.findAllList();
        return users;
    }

    /**
     * 访问role-ms微服务,获取角色列表
     * @return 角色列表
     */
    @RequestMapping(value = {"/role/list"}, method = RequestMethod.GET)
    public Object roleList() {
        return roleFeignClient.list();
    }

    /**
     * 访问role-ms微服务,保存角色数据
     * @param role 待保存的角色数据
     * @return 数据保存结果
     */
    @RequestMapping(value = {"/role/insert"}, method = RequestMethod.POST)
    public Object roleInsert(@RequestBody Role role) {
        return roleFeignClient.insert(role);
    }

}

测试

通过postman测试服务,结果如下:

猜你喜欢

转载自blog.csdn.net/greedystar/article/details/88993324