OpenFeign是什么?
Spring Cloud OpenFeign 是一个声明式的 HTTP 客户端,它使得编写 Web 服务客户端变得更加简单
OpenFeign的作用?
通过定义一个接口,并使用注解来声明对远程服务的调用,而无需编写大量的底层 HTTP 通信代码。例如,你可以在接口方法上使用注解来指定请求的方法(GET、POST 等)、请求路径、请求参数等
OpenFeign的使用
① openFeign的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
需求:现在有 A B 两个服务,需要在B服务中调用A服务里面的接口
首先要确保 A B 两个服务都注册到注册中心
在A服务中编写的代码为:
@RestController
public interface FeignClient {
@GetMapping("/api/hello")
Person hello(@RequestParam Integer id);
@PostMapping("/api/welcome")
List<Person> list(@RequestBody Person person);
}
@Service
public class FeignClientImpl implements FeignClient {
@Autowired
private PersonService service;
@GetMapping("/api/hello")
public Person hello(Integer id) {
return service.getById(id);
}
@PostMapping("/api/welcome")
public List<Person> list(Person person) {
LambdaQueryWrapper<Person> wrapper = Wrappers.lambdaQuery();
wrapper.eq(ObjectUtils.isNotEmpty(person.getSex()),Person::getSex,person.getSex());
wrapper.eq(ObjectUtils.isNotEmpty(person.getStyle()),Person::getStyle,person.getStyle());
return service.list(wrapper);
}
}
B服务中编写的代码为
@FeignClient(name = "A") // 确保这里的 name 指向服务 A
public interface AServiceClient {
@GetMapping("/api/hello")
Person hello(@RequestParam Integer id);
}
@RestController
public class BController {
@Autowired
private AServiceClient aServiceClient;
@GetMapping("/api/greet")
public Person greet(@RequestParam Integer id) {
return aServiceClient.hello(id);
}
}
在B服务的启动类上加入@EnableFeignClients注解
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.example.websocket.feign")
public class WebsocketApplication {
public static void main(String[] args) {
SpringApplication.run(WebsocketApplication.class, args);
}
}
最后访问B服务中的: http://ip:port/api/greet 地址 即可调用到A服务的接口