1.引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
2.在启动类上添加上openFeign客户端注解赋能openFeign
@SpringBootApplication
@EnableFeignClients //赋能openFeign
@EnableDiscoveryClient
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
3.接下来创建对应的feign客户端接口,将服务生产者拉取到本服务
//这里注解括号内,是你要赋能此接口向nacos注册的服务名称
@FeignClient("user-service")
public interface UserFeign {
//这里采用springMVC的接口风格赋能方法,使得这个方法已经变成了服务生产者
//这里注意你的接口路径要写全,不要忽略@RequestMapping后面的路径(如果你写了的话)
@GetMapping("user/getUserById")
User getUserById(@RequestParam("userId") Integer userId);
}
4.最后在对应的service中,注入你的feign接口,并调用你已经赋能的方法
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private UserFeign userFeign;
@Override
public Order getUserOrder(Integer userId) {
System.out.println("测试服务间调用");
return new Order(userFeign.getUserById(userId),1);
}
}
5.注意
在编写feign接口时,
- 方法为get请求,要添加@RequestParam注解;参数为对象时只能添加@SpringQureyMap注解
- 注意要将参数和返回的结果对象实现序列化接口