1. 程式人生 > >SpringCloud之服務呼叫(feign)

SpringCloud之服務呼叫(feign)

前言

前一篇介紹了使用Ribbon的RestTemplate進行服務呼叫的使用方式。除了這種方式進行服務呼叫以外還可以通過Feign進行呼叫,本篇文章就是簡單介紹一下如何使用Feign進行服務呼叫。根據前一篇文章所用專案進行修改。

Feign使用流程

1.pom檔案引入依賴

        <!--feign依賴-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

備註:根據feign版本的不同,名稱可能不一樣,可以到官方進行檢視feign的maven。
2.入口新增@EnableFeignClients

package com.ckmike.order_service;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableFeignClients
public class OrderServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderServiceApplication.class, args);
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

3.編寫商品服務客戶端介面

package com.ckmike.order_service.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @ClassName ProductClient商品服務客戶端
 * @Description TODO:描述該介面職責
 * @Author ckmike
 * @Date 18-11-22 下午4:10
 * @Version 1.0
 * @Copyright ckmike
 **/
@FeignClient(name="product-service")
public interface ProductClient {

    @GetMapping("/api/v1/product/find")
    String findById(@RequestParam(value = "id") int id);
}

備註:商品服務客戶端介面的路由必須與商品服務對應路由保持一致。

訂單服務介面實現

package com.ckmike.order_service.service.impl;

import com.ckmike.order_service.domain.ProductOrder;
import com.ckmike.order_service.service.OrderService;
import com.ckmike.order_service.service.ProductClient;
import com.ckmike.order_service.utils.JsonUtil;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * OrderServiceImpl 簡要描述
 * <p> TODO:描述該類職責 </p>
 *
 * @author ckmike
 * @version 1.0
 * @date 18-11-7 下午11:55
 * @copyright ckmike
 **/
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ProductClient productClient;

    @Override
    public ProductOrder saveForRibbon(int userId, int productId) {
        // 獲取商品資訊
        Map<String,Object> obj = restTemplate.getForObject("http://product-service/api/v1/product/find?id="+productId,Map.class);

        ProductOrder productOrder = new ProductOrder();
        productOrder.setCreateTime(new Date());
        productOrder.setUserId(userId);
        productOrder.setTradeNo(UUID.randomUUID().toString());

        productOrder.setPrice(Double.parseDouble(obj.get("price").toString()));

        productOrder.setProductName(obj.get("name").toString());
        return productOrder;
    }

    @Override
    public ProductOrder saveForFeign(int userId, int productId) {
        String response = this.productClient.findById(productId);
        JsonNode obj = JsonUtil.str2JsonNode(response);

        ProductOrder productOrder = new ProductOrder();
        productOrder.setCreateTime(new Date());
        productOrder.setUserId(userId);
        productOrder.setTradeNo(UUID.randomUUID().toString());

        productOrder.setPrice(Double.parseDouble(obj.get("price").toString()));

        productOrder.setProductName(obj.get("name").toString());
        return productOrder;
    }
}

截圖

啟動EurekaServer、ProductService、OrderService.
SpringCloud之服務呼叫(feign)

訪問介面:
http://ckmikepc.lan:8781/api/v1/order/saveforfeign?user_id=1&product_id=1
SpringCloud之服務呼叫(feign)

總結一下:
Feign是通過Ribbon實現的,具體可以檢視相應的程式碼。更多詳細資訊請檢視Feign相應文件,會對你理解Feign的使用和實現有很大幫助。在學會如何使用feign後,建議閱讀一下Feign的原始碼,看看別人是怎麼寫出這種東西的。