RestTemplate工具類根據服務名發送請求


  要使用RestTemplate 根據服務名發送請求的話需要 使用  @LoadBalanced  這個注解,用了這個注解的RestTemplate就不用使用  ip 來請求了,首先要創建一個配置類

  

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: dx
 * @Description:
 * @Date: 2020/2/14 0014
 * @Version: 1.0
 */
@Configuration
public class RestTemplateConfig {

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

  

  然后是工具類
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.xin.xunwu.base.Exception.BizException;
import com.xin.xunwu.base.response.ApiResult;
import com.xin.xunwu.entity.ServiceApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;


/**
 * @author dx
 */
@Slf4j
@Component
public class RestUtil {

    public static final String HTTP = "http://";

    public static final String[] HTTP_METHODS = {"POST", "GET"};

    @Resource
    private RestTemplate restTemplate;

    public ResponseEntity<JSONObject> restQuery(ServiceApi serviceApi) {
        String methodStr = serviceApi.getMethod().toUpperCase();
        // 請求類型錯誤
        if (!Arrays.asList(HTTP_METHODS).contains(methodStr)) {
            throw new BizException(ApiResult.getErrorResult("30059"));
        }
        // 根據服務名和路徑拼接url
        String url = HTTP + serviceApi.getService() + serviceApi.getPath();
        MultiValueMap<String, String> params = null;
        MultiValueMap<String, String> headers = null;

        // 轉換參數
        try {
            params = jsonToMap(serviceApi.getParams());
            headers = jsonToMap(serviceApi.getHeader());
        } catch (Exception e) {
            e.printStackTrace();
            // json 轉換錯誤
            throw new BizException(ApiResult.getErrorResult("30060"));
        }
        HttpMethod method = HttpMethod.resolve(methodStr);
        return restQuery(url, params, method, headers);
    }

    private MultiValueMap<String, String> jsonToMap(String jsonStr) {
        if (jsonStr == null) {
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        MultiValueMap<String, String> result = new LinkedMultiValueMap<>();
        jsonObject.forEach((key, value) -> result.add(key, value.toString()));
        return result;
    }

    private ResponseEntity<JSONObject> restQuery(String url, MultiValueMap<String, String> paramsMap,
                                                 HttpMethod method, MultiValueMap<String, String> headerMap) {
        ResponseEntity<JSONObject> responseEntity = null;
        // 轉換編碼格式
        List<HttpMessageConverter<?>> list = restTemplate.getMessageConverters();
        for (HttpMessageConverter<?> httpMessageConverter : list) {
            if (httpMessageConverter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter)
                        httpMessageConverter).setDefaultCharset(StandardCharsets.UTF_8);
                break;
            }
        }

        // 設置頭信息
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON));

        // 頭信息非空的話,添加頭信息
        Optional.ofNullable(headerMap).ifPresent(httpHeaders::addAll);

        // 設置頭信息和請求參數
        HttpEntity<MultiValueMap<String, String>> params = new HttpEntity<>(paramsMap, httpHeaders);
     // 如果是get請求的話需要把參數拼到url上
        if(method.equals(HttpMethod.GET)){
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
            paramsMap.forEach(builder::queryParam);
            url = builder.build().encode().toString();
        }

        try {
            responseEntity = restTemplate.exchange(url, method, params, JSONObject.class);
        } catch (Exception e) {
            // 請求失敗
            log.warn("restTemplate  error [message] {}", e.getMessage());
        }
        return responseEntity;
    }
}

  然后是用到的一個實體類,這個不是必須的,可以根據自己的需要修改,我這是業務需求

  

import lombok.Getter;
import lombok.Setter;
import javax.persistence.Column;
import javax.persistence.Id;
import java.util.Date;

/** 
 @author Generator 
 @since 2020-02-13T10:38:02.789 
 **/
@Getter
@Setter
public class ServiceApi {
    /**
     * 通過ID生成器自動生成
     */
    @Id
    private Long id;

    /**
     * 編號
     */
    private String number;

    /**
     * 服務名(注冊服務名稱)
     */
    private String service;

    /**
     * 方法
     */
    private String method;

    /**
     * 路徑
     */
    private String path;

    /**
     * 頭信息
     */
    private String header;

    /**
     * 請求體
     */
    private String body;

    /**
     * 參數
     */
    private String params;

    /**
     * 接口類型(drop:下拉選 verify:驗證)
     */
    private String type;

    /**
     * 備注
     */
    private String remark;

    /**
     * 刪除標記(0:未刪除;1:已刪除)
     */
    @Column(name = "delete_flg")
    private String deleteFlg;

    /**
     * 創建時間
     */
    @Column(name = "create_time")
    private Date createTime;

    /**
     * 創建者
     */
    private Long creator;

    /**
     * 更新時間
     */
    @Column(name = "update_time")
    private Date updateTime;

    /**
     * 更新者
     */
    private Long updator;
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM