创建服务工程:cloud-consumer-feign-consumer80;
导入依赖:引入 web、openfeign、eureka-discovery-client 等相关依赖
配置 application.yml
server:
port: 80
spring:
application:
name: cloud-consumer-feign-consumer80
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:7001/eureka/
在主启动类上加:
@EnableFeignClients,
开启 Feign 支持,实现基于接口的远程
调用
@SpringBootApplication
@EnableFeignClients
public class CloudConsumerFeignConsumer80Application {
public static void main(String[] args) {
SpringApplication.run(CloudConsumerFeignConsumer80Application.class, args);
}
}
在 service 层添加一个接口
@FeignClient(value = "CLOUD-EUREKA-PROVIDER8001")//值为被调用eureka名
public interface FeignClinentDA {
//方法及@RequestMapping映射要和被调用接口保持完全一致
@GetMapping("/user/find")
public User findUser(@RequestParam("id") Integer id);
}
关于Feign客户端的几点说明:
1.首先这是一个接口,Feign会通过动态代理,帮我们生成实现类。这点跟mybatis的mapper很像2.@FeignClient ,声明这是一个Feign客户端,同时通过 value 属性指定服务名称3.接口中的定义方法,完全采用SpringMVC的注解,Feign会根据注解帮我们生成URL,并访问获取结果4.@GetMapping中的/movie,请不要忘记;因为Feign需要拼接可访问的地址
修改 service 层类,将 RestTemplate 改成 Feign 调用方式
@Service
public class OrderService {
@Autowired
private OrderDao orderDao;
@Autowired
FeignClinentDA feignClientda;
public Order findOrder(Integer id){
return orderDao.findOrder(id);
}
public Map finOrderAndUser(Integer id){
Order order = orderDao.findOrder(id);
Map map = new HashMap<>();
User user = feignClientda.findUser(id);
map.put("order",order);
map.put("user",user);
return map;
}
}
Feign 远程调用注意点
需要注意:使用 Feign 进行远程调用的时候,如果需要给被调用方传递参数信息,就只能使用 @ReuestMapping 注解或者 @PostMapping 注解,不能使用 @GetMapping 注解若使用@GetMapping 注解,需要在形参上加 @RequestParam()注解