spring cloud微服务创建(二)--远程调用feigin

一、feigin使用(前提该项目是一个cloud项目,且包含注册中心客户端)
步骤:
1.1、依赖引入
<!--引入feign依赖  -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
1.2 、启动类添加 @EnableFeignClients 注解 开启feigin

开启feigin

1.3 、创建一个包,接口xxxclient
1.4 、该接口上面添加
    @FeignClient(name ="product-service") 
    public interface ProductClient {}
注:name=“注册服务名称” 同“spring.application.name” 一致

eg: order-service服务调用product-service中的findByid接口

@FeignClient(name ="product-service") //[A]
public interface ProductClient {

    @RequestMapping("api/vi/product/find")//[B]
    String findByid(@RequestParam(value = "id")int id);//[C]

}

A: @FeignClient用于通知Feign组件对该接口进行代理(不需要编写接口实现),使用者可直接通过@Autowired注入。属性可以是name,也可以是value都是表示被调用的相应的服务名称

B: @RequestMapping表示在调用该方法时需要向api/vi/product/find发送Post请求。必须和被调用的服务接口路径一致

C: 参数要与被调用接口参数一致。


此时你需要调用那个服务的接口就需要填写相应的接口信息就可以了

feigin的使用 就和service接口使用一般 注入调用接口(feigin是不需要实现类的)

@Autowired
   private ProductClient productClient;
    /**
     *
     * @param userId
     * @param productId
     * @return
     */
    @Override
    public ProductOrder save(int userId, int productId) {
       /* //获取商品详情 TODO
        Map<String,Object> map = restTemplate.getForObject("http://product-service:8771/api/vi/product/find?id="+productId,Map.class);
       */
       String response =  productClient.findByid(productId);
       JsonNode jsonNode = JsonUtils.str2JsonNode(response);
        ProductOrder productOrder = new ProductOrder();
        productOrder.setCreateTime(new Date());
        productOrder.setUserId(userId);
        productOrder.setTradeNo(UUID.randomUUID().toString());
        productOrder.setProductName(jsonNode.get("pname").toString());
        return productOrder;
    }

配置文件包含基本信息如下

server:
  port: 8781
#注册中心地址
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
#订单服务名称
spring:
  application:
    name: order-service

注:被调用的服务和调用方都必须要在同一个注册中心eureka ,两者都必须要启动且注册成功!

关于注册中心的创建和使用请参考博文:https://blog.csdn.net/weixin_42083036/article/details/90903811

猜你喜欢

转载自blog.csdn.net/weixin_42083036/article/details/90904024