微服务Spring Cloud OpenFeign服务调用

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服务的接口

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值