OpenFeign声明式调用实战指南
使用
openFegin的使用还是比较简单的~
引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign-core</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-ribbon</artifactId>
</exclusion>
</exclusions>
</dependency>
启动类加注解
//指定扫描包路径
@EnableFeignClients(basePackages = "net.nxe")
@SpringBootApplication(scanBasePackages = "net.nxe")
public class UCServer {public static void main(String[] args) {SpringApplication.run(UCServer.class);}
}
写接口
@PostMapping("/test")
public void test(@RequestBody EmployeeEffectiveMemberParam param) {employeeEffectiveMember.setCreateTime(new Date());employeeEffectiveMemberService.save(employeeEffectiveMember);
}
定义OpenFegin接口
保证和定义的接口一致就可以了~~
@FeignClient(value = "test")
public interface EmployeeEffectiveMemberService {@PostMapping("/test")void addEmployeeEffectiveMember(@RequestBody EmployeeEffectiveMemberParam param);
}
补充
OpenFegin远程调用无数据
检查Feign客户端接口定义
确保Feign客户端的接口定义与原接口完全一致,包括:URL路径:路径中的参数是否使用 {variable} 占位符,并用 @PathVariable 或@RequestParam 正确绑定。
HTTP方法:如 @GetMapping、@PostMapping 等。
参数注解:区分 @PathVariable、@RequestParam、@RequestBody 的使用场景。
// 错误示例:缺少@RequestParam注解
@GetMapping("/data")
List<Data> getData(String id); // 正确示例
@GetMapping("/data")
List<Data> getData(@RequestParam("id") String id);
@SpringQueryMap注解解释
@SpringQueryMap 是 Spring Cloud OpenFeign 中的一个注解,用于处理 HTTP 请求参数。它将对象的属性自动映射为 URL 查询参数
使用场景:
假设你需要发出一个GET请求,并传递多个查询参数。如果你使用 @SpringQueryMap,可以更方便地将一个对象的属性转换为查询参数,而不需要手动设置每一个参数。会将对象的属性 (name, age, location) 会自动映射到 GET 请求的查询参数