使用feign远程调用小记

本文指导如何在Feign中正确配置接口调用,包括@EnableFeignClients启用、接口定义的注解如@PostMapping和@RequestParam的使用,以及处理单参数时的注解规范。遇到空指针异常?这里告诉你解决方案。

当我们要使用feign远程调用其他项目的接口时,要在启动类上注解@EnableFeignClients

然后将创建一个接口要,将要调用的接口的注解和返回值类型、函数名那两行粘过去。这里,要尤其注意,粘过去之后,如果函数里有参数,则一定要在参数前声明一个注解表明你的参数名,即使只有一个参数也要写注解声明。例如:

@PostMapping("/user/login")
    public AppResponse<UserRespVo> login(@RequestParam("loginacct")String loginacct,@RequestParam("password")String password);

我就是以为只有一个参数可以不写@RequestParam,然后就报空指针异常,意思就是取不到结果,加上了就行了。

Feign是一个声明式的HTTP客户端,用于优雅地实现HTTP请求的发送,以下是Feign远程调用使用方法: #### 1. 添加依赖 在`pom.xml`中添加Spring Cloud OpenFeign的依赖: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> ``` #### 2. 启用Feign客户端 在Spring Boot应用的主类上添加`@EnableFeignClients`注解,以启用Feign客户端功能: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication @EnableFeignClients public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` #### 3. 定义Feign客户端接口 创建一个接口,并使用`@FeignClient`注解来指定要调用的服务名或URL。例如: ```java import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @FeignClient(name = "user-service") public interface UserFeignService { @GetMapping("/users/{id}") User getUserById(@PathVariable("id") Long id); } class User { private Long id; private String name; // getters and setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` 如果要调用固定URL的服务,可以使用`url`属性: ```java @FeignClient(name = "exampleClient", url = "http://example.com/api") public interface ExampleClient { @GetMapping("/resource") String getResource(); } ``` #### 4. 在服务中使用Feign客户端 在需要进行远程调用的服务中注入Feign客户端接口,并调用其方法: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserFeignService userFeignService; public User getUser(Long id) { return userFeignService.getUserById(id); } } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fake-WTX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值