欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

远程调用--->RestTemplate

程序员文章站 2022-04-28 16:52:09
...

配置RestTemplate

@Configuration
public class RestTemplateConfing {


    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(0);// 设置建立连接超时时间
        requestFactory.setReadTimeout(0);// 设置等待返回超时时间
        restTemplate.setRequestFactory(requestFactory);
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }
}

远程调用工具类:

package cn.zy.util;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: spring_cloud
 * @description: 远程调用工具类
 * @author: chenhu
 * @create: 2021-01-25 13:34
 **/
public class RestTemplateUtils {
    //一些自定义的请求头参数
    public static final String supplierID = "";
    public static final String interfacekey = "";

    static RestTemplate restTemplate = new RestTemplate();


    /**
     * get请求调用
     *
     * @param url   :访问地址
     *              get请求直接带地址中品参数:http://localhost:8081/resume/findResume?userId=" + userId
     * @param clazz :返回值类型
     * @param <T>
     * @return
     */
    public static <T> T get(String url, Class<T> clazz) {
        return restTemplate.getForObject(url, clazz);
    }

    /**
     * post请求调用
     *
     * @param url   :访问地址
     * @param clazz 返回值类型
     * @param param 传递参数
     *              传递参数的map使用:MultiValueMap<String, Object> paramMap3 = new LinkedMultiValueMap();
     * @return
     */
    public static <T> T post(String url, MultiValueMap<String, Object> param, Class<T> clazz) {
        return execute(param, url, HttpMethod.POST, clazz);
    }

    /**
     * put请求调用
     *
     * @param url   :访问地址
     * @param clazz 返回值类型
     * @param param 传递参数
     *              传递参数的map使用:MultiValueMap<String, Object> paramMap3 = new LinkedMultiValueMap();
     * @return
     */
    public static <T> T put(String url, MultiValueMap<String, Object> param, Class<T> clazz) {
        return execute(param, url, HttpMethod.PUT, clazz);
    }

    /**
     * delete请求调用
     *
     * @param url   :访问地址
     * @param clazz 返回值类型
     * @param param 传递参数
     *              传递参数的map使用:MultiValueMap<String, Object> paramMap3 = new LinkedMultiValueMap();
     * @return
     */
    public static <T> T dale(String url, MultiValueMap<String, Object> param, Class<T> clazz) {
        return execute(param, url, HttpMethod.DELETE, clazz);
    }

    /**
     * 通用执行方法(只适用于:post,put,delete,不适用于get方法)
     *
     * @param param  请求参数:可以添加一些常量请求值
     * @param url    访问的url
     * @param method 请求接口的类型
     * @param clazz  返回值类型
     * @return
     */
    private static <T> T execute(MultiValueMap<String, Object> param, String url, HttpMethod method, Class<T> clazz) {
        HttpHeaders headers = getDefaultHeader();
        Map<String, Object> requestor = getDefaultParam();
        param.add("requestor", requestor);
        param.add("supplierID", supplierID);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity(param, headers);
        ResponseEntity<T> response = restTemplate.exchange(url, method, requestEntity, clazz);
        return response.getBody();
    }

    /**
     * 获取默认的头请求信息
     *
     * @return
     */
    private static HttpHeaders getDefaultHeader() {
        String timestamp = "" + System.currentTimeMillis();
        String signature = EncoderByMd5(supplierID + timestamp + interfacekey);
        HttpHeaders headers = new HttpHeaders();
        headers.add("signature", signature);
        headers.add("timestamp", timestamp);
        return headers;
    }

    /**
     * 获取默认的参数
     *
     * @return
     */
    private static Map<String, Object> getDefaultParam() {
        Map<String, Object> defParam = new HashMap<>();
        defParam.put("invoker", "xx");
        defParam.put("operatorName", "xx");
        return defParam;
    }

    /**
     * 通过MD5加密
     *
     * @param str
     * @return
     */
    private static String EncoderByMd5(String str) {
        if (str == null) {
            return null;
        }
        try {
            // 确定计算方法
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            BASE64Encoder base64en = new BASE64Encoder();
            // 加密后的字符串
            return base64en.encode(md5.digest(str.getBytes("utf-8"))).toUpperCase();
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            return null;
        }
    }
}

测试:
服务提供者:

    @GetMapping("/test3")
    public String test3(@RequestParam(value = "id", required = false) Integer id
            , @RequestParam(value = "name", required = false) String name) {
        System.err.println(id);
        System.err.println(name);
        Guke gukeById = gukeMapper.getGukeById(5L);
        return gukeById.toString();
    }

    @PostMapping("/test4")
    public String test4(Ce ce) {
        System.err.println(ce);
        Guke gukeById = gukeMapper.getGukeById(5L);
        return gukeById.toString();
    }

    @PutMapping("/test5")
    public String test5(Ce ce) {
        System.err.println(ce);
        Guke gukeById = gukeMapper.getGukeById(5L);
        return gukeById.toString();
    }

    @DeleteMapping("/test6")
    public String test6(Ce ce) {
        System.err.println(ce);
        Guke gukeById = gukeMapper.getGukeById(5L);
        return gukeById.toString();
    }

服务调用:

    @ResponseBody
    @RequestMapping(value = "/getCheFenYears", method = RequestMethod.GET)
    public void getCheFenYears(HttpServletRequest request) {
        Map<String, String> parameterMap = getParameterMap(request);

        //get========================调用
        Map<String, String> parmasget = new HashMap<String, String>();
        parmasget.put("name", "李大雷");
        String s = httpLongCall.get("http://localhost:8080/account/findAccountByName", parmasget);


        //post========================调用
        Map<String, String> parmas = new HashMap<String, String>();
        parmas.put("name", "李大雷");
        String post = httpLongCall.post("http://localhost:8080/account/findAccountByNamepos", parmas);

        //put===================调用
        Map<String, String> parmas2 = new HashMap<String, String>();
        parmas2.put("name", "李大雷");
        String put = httpLongCall.put("http://localhost:8080/account/findAccountByName03", parmas2);

        //delete===============================调用
        Map<String, String> parmas3 = new HashMap<String, String>();
        parmas3.put("name", "李大雷dele");
        String dale = httpLongCall.dale("http://localhost:8080/account/findAccountByName04", parmas3);
        try {
            System.err.println("执行" + put);
        } catch (Exception e) {
            log.error("获取NIG vin 号下载数据异常!", e);
            ResponseUtil.fail(e);
        }
    }