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的源碼,看看別人是怎麼寫出這種東西的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章