首页 > 其他 > 详细

FeignClient接口封装

时间:2020-03-14 00:09:06      阅读:698      评论:0      收藏:0      [点我收藏+]

Feign是一种声明式、模块化的HTTP客户端。在SpringCloud中使用Feign,可以做到使用HTTP请求访问远程服务,就像调用本地方法一样,开发者完全无感知在进行HTTP请求调用。

1.接口定义
首先在单独的module中定义接口:

@FeignClient(name ="com.johar.feign-test", path ="/user", url="${account-service-endpoint}")

public interface User {

@GetMapping("/{userId}")

public BaseResponsefindById(@PathVariable("userId")int userId);

@PostMapping("/add")

public BaseResponsecreateUser(@RequestBody UserDto userDto);

}

FeignClient常用的注解属性如下:

(1)name:指定FeignClient的名称,如果项目使用了Ribbon,name属性会作为微服务的名称,用于服务发现。

(2)url:一般用于调试,手动指定@FeignClient的调用地址。

(3)path:定义当前的FeignClient的统一前缀。

(4)configuration:Feign的配置类,可以自定义Feign的Encoder,Decode,LogLevel,Contract。

(5)fallbckFactory:实现每个接口通用的容错逻辑,减少重复代码。

2.实现定义的接口
在另外一个module中实现定义的接口:

@RestController

@RequestMapping("/user")

public class UserControllerimplements User {

@GetMapping("/{userId}")

@Override

public BaseResponsefindById(@PathVariable("userId")int userId) {

UserDto userDto = UserDto.builder().age(29).id(userId).name("johar").sex(1).build();

    BaseResponse result =new BaseResponse();

    result.setData(userDto);

    return result;

}

@PostMapping("/add")

@Override

public BaseResponsecreateUser(@RequestBody UserDto userDto) {

userDto.setId(1);

    BaseResponse result =new BaseResponse();

    result.setData(userDto);

    return result;

}

}

3.使用FeignClient调用接口

3.1 引入接口包

org.springframework.cloud

spring-cloud-starter-netflix-ribbon

com.johar

feign-api

0.0.1-SNAPSHOT

3.2 在启动类开启FeignClients

@EnableFeignClients(basePackages = "com.johar.feignapi")

3.3 FeignClient接口调用

@SpringBootApplication

@EnableFeignClients(basePackages ="com.johar.feignapi")

public class FeignClientApplicationimplements CommandLineRunner {

public static void main(String[] args) {

SpringApplication.run(FeignClientApplication.class, args);

}

@Autowired

private Useruser;

@Override

public void run(String... args)throws Exception {

System.out.println(user.findById(1));

    System.out.println(user.createUser(UserDto.builder().sex(2).name("Anna").age(28).build()));

}

}

FeignClient接口封装

原文:https://www.cnblogs.com/Johar/p/12489785.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!