springboot+mybatis 调用第三方数据基本流程

1.对接第三方接口流程:
1):一般对接第三方接口或者被第三方调用,都会有一个授权key 或者登录token之类的东西 保证数据在传输过程中的安全性,和拥有一些什么权限的设定。
2):controller类:

 @PostMapping("/getShipId")
    public Result getShipId(@RequestBody GetShipIdShipRequestVo vo) {
        log.info("query controller" + JSON.toJSONString(vo));
        Map result = null;
        Object value = null;
        try {
        //把参数赋值到Map中去,用于参数的传递,传递到serice中
            Map map = MapUtils.beanToMap(vo, Constant.LIST_FIELD);
            result = shipXyDataInfoService.queryShipId(map);
            //取map中key为data的值
            for (String key : result.keySet()) {
                value = result.get("data");
            }
        } catch (Exception e) {
            log.error("getShipId Exception:{}", e);
        }
        return ResultUtil.success(value);
    }

MapUtils工具类:(把bean To Map)

package com.finance.cmp.dac.service.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.springframework.cglib.beans.BeanMap;


public class MapUtils {

	public static ConcurrentMap beanMapCache = new ConcurrentHashMap();

	public static BeanMap getBeanMap(Object object) {
		BeanMap beanMap = beanMapCache.get(object.getClass().getName());
		if (beanMap == null) {
			beanMap = BeanMap.create(object);
			beanMapCache.put(object.getClass().getName(), beanMap);
		}
		return beanMap;
	}

	// 如果使用BeanMap缓存,这个性能最好。
	public static Map beanToMap(Object object,Set sets) {

		BeanMap beanMap = getBeanMap(object);
		beanMap.setBean(object);
		@SuppressWarnings("unchecked")
		Map toMap = beanMap;
//
//		for (Entry entry : toMap.entrySet()) {
//			if (entry.getValue() != null) {
//					toMap.put(entry.getKey(), entry.getValue());
//			}
//		}
		Map resultmap=new HashMap();
		if(sets==null||sets.size()<1) {
			for (Entry entry : toMap.entrySet()) {
				if (entry.getValue() != null ) {
					resultmap.put(entry.getKey(), entry.getValue());
				}
			}
		}else{
			for (Entry entry : toMap.entrySet()) {
				if (entry.getValue() != null && !sets.contains(entry.getKey())) {
					resultmap.put(entry.getKey(), entry.getValue());
				}
			}
		}
		return resultmap;
	}
	
	
	
	
	
	public static Map ConvertObjToMap(Object obj){
		  Map reMap = new HashMap();
		  if (obj == null)
		   return null;
		  Field[] fields = obj.getClass().getDeclaredFields();
		  try {
		   for(int i=0;i T map2Bean(T t, Map map) throws Exception {
		Class clazz = t.getClass();
		// 实例化类
		T entity = (T) clazz.newInstance();
		Set keys = map.keySet();
		// 变量map 赋值
		for (String key : keys) {
			String fieldName = key;
			// 判断是sql 还是hql返回的结果
			if (key.equals(key.toUpperCase())) {
				// 获取所有域变量
				Field[] fields = clazz.getDeclaredFields();
				for (Field field : fields) {
					if (field.getName().toUpperCase().equals(key))
						fieldName = field.getName();
					break;
				}
			}
			// 设置赋值
			try {
				// 参数的类型 clazz.getField(fieldName)
				Class paramClass = clazz.getDeclaredField(fieldName)
						.getType();
				// 拼装set方法名称
				String methodName = "set"
						+ fieldName.substring(0, 1).toUpperCase()
						+ fieldName.substring(1);
				// 根据名称获取方法
				Method method = clazz.getMethod(methodName, paramClass);
				// 调用invoke执行赋值
				method.invoke(entity, map.get(key));
			} catch (Exception e) {
				System.out.println(e.toString());
			}
		}

		return entity;
	}

	public static  T mapBind(Map map, T t) throws Exception {

		// 获得传入vo的Class方法
		Class newClass = t.getClass();
		// 得到vo中所有的成员变量
		Field[] fs = newClass.getDeclaredFields();
		// 方法变量
		String methodName = null;
		// map的value值
		Object mapValue = null;
		// 参数类型
		String parameterType = null;
		// 查找方法时需要传入的参数
		Class[] parameterTypes = new Class[1];
		// 执行invoke方法时需要传入的参数
		Object[] args = new Object[1];
		// 取得Map的迭代器
		Iterator it = map.keySet().iterator();
		while (it.hasNext()) {
			// 取出map的key值
			String key = (String) it.next();
			if (key != null) {
				for (int i = 0; i < fs.length; i++) {
					if (key.equals(fs[i].getName())) {
						// 拼set方法名
						methodName = "set"
								+ key.replaceFirst(key.substring(0, 1), key
										.substring(0, 1).toUpperCase());
						try {
							// 得到vo中成员变量的类型
							parameterTypes[0] = fs[i].getType();
							parameterType = parameterTypes[0].toString();
							// 找到vo中的方法
							Method method = newClass.getDeclaredMethod(
									methodName, parameterTypes);
							mapValue = map.get(key);
							// 下面代码都是参数类型是什么,如果有需求可以自行增加
							// 当set方法中的参数为int或者Integer
							if (parameterTypes[0] == Integer.class
									|| parameterTypes[0] == int.class) {
								if (mapValue instanceof Integer) {
									args[0] = mapValue;
								} else {
									args[0] = Integer
											.parseInt((String) mapValue);
								}
								// 当set方法中的参数为Date
							} else if (parameterTypes[0] == Date.class) {
								if (mapValue instanceof Date) {
									args[0] = mapValue;
								} else {
									SimpleDateFormat sdf = new SimpleDateFormat(
											"yyyy-MM-dd");
									args[0] = sdf.parse((String) mapValue);
								}
								// 当set方法中的参数为Float
							} else if (parameterTypes[0] == double.class
									|| parameterTypes[0] == Double.class) {
								if (mapValue instanceof Double) {
									args[0] = mapValue;
								} else {
									args[0] = Double
											.parseDouble((String) mapValue);
								}
								// 当set方法中的参数为其他
							} else if (parameterTypes[0] == String.class) {

								if (mapValue instanceof String[]) {

									String[] tempArray = (String[]) mapValue;
									String result = "";
									for (int m = 0; m < tempArray.length; m++) {
										result = result + tempArray[m] + ",";
									}
									result = result.substring(0,
											result.length() - 1);
									args[0] = result;

								} else {
									args[0] = (String) mapValue;
								}
							} else {
								args[0] = mapValue;
							}
							// 执行set方法存储数据
							method.invoke(t, args);

						} catch (SecurityException e) {
							throw new SecurityException("[mapBind]安全异常:" + e);
						} catch (NoSuchMethodException e) {
							throw new NoSuchMethodException(
									"[mapBind]Vo中无此方法异常" + e);
						} catch (IllegalArgumentException e) {
							throw new Exception("VO中" + key + "属性类型"
									+ parameterType + "与Map中值为" + mapValue
									+ "的类型不匹配");
						} catch (IllegalAccessException e) {
							throw new IllegalAccessException(
									"[mapBind]IllegalAccessException异常");
						} catch (ParseException e) {
							throw new ParseException(
									"[mapBind]ParseException异常", 0);
						}
					}
				}
			}
		}
		return t;
	}
	
	
	

}

3):seivice类:

a.serivce接口:参数为map 返回也为map
Map queryShipId(Map query);
b.service实现类:

 @Override
    public Map queryShipId(Map query) {
        log.info("query service : " + query);

        //一般把第三方的接口信息存在数据库
        List channelApis = (List) redisCacheService.get(Constant.REDIS_CHANNELAPI_PREFIX);
        for (TChannelApi t : channelApis) {
            if (t.getApiName().equals("apicall/QueryShip")) {
                log.info("url : " + t.getApiFullUrl());
                query.put("url", t.getApiFullUrl());
                query.put("apiId", t.getId());
                query.put("channelCode", t.getChannelCode());
            }
        }
        //正在的调三方
        Object obj = queryShipXyDataService.queryShipId(query);
        log.info("result Object :" + obj);
        Map mapRe = (Map) obj;

        return mapRe;
    }

c.真正调: 使用RestTemplate http方式

 @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private TDataServiceResultMapper tDataServiceResultMapper;
    @Autowired
    private TLogSubscriberMapper tLogSubscriberMapper;

    @Override
    public Map queryShipId(Map query) {
        log.info("query third : " + query);
        Map resultMap = new HashMap<>();
        String url = query.get("url") + "";
        log.info("query third url: " + url);
        String kw = query.get("kw") + "";
        log.info("query third kw: " + kw);
        String v = query.get("v") + "";
        log.info("query third kw: " + v);
        String k = query.get("k") + "";
        log.info("query third k: " + k);
        String enc = query.get("enc") + "";
        log.info("query third enc: " + enc);
        Integer apiId = Integer.parseInt(query.get("apiId") + "");
        log.info("query third apiId: " + apiId);
        String channelCode = query.get("channelCode") + "";
        log.info("query third channelCode: " + channelCode);
        HttpHeaders hd = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        hd.setContentType(type);
        //传递参数
        JSONObject json = new JSONObject();
        long timeTemp = System.currentTimeMillis();
        json.put("v", v);
        json.put("k", k);
        json.put("kw", kw);
        json.put("enc", enc);
        HttpEntity entity = new HttpEntity<>(json.toString(), hd);
        ResponseEntity resultEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class, new HashMap());
        String reultObj = resultEntity.getBody();
        log.info("query third result : " + reultObj);
        JSONObject result = JSONObject.parseObject(reultObj);
        //data是个数组则用JSONArray接受,不是数组则用JSONObject
        JSONArray result1 = result.getJSONArray("data");

//把请求结果存入请求表中记录
        TLogSubscriber logSubscriber = new TLogSubscriber();
        logSubscriber.setChannelApiId(apiId.toString());
        logSubscriber.setRequestNo(String.valueOf(System.currentTimeMillis()));
        logSubscriber.setApiFullUrl(url);
        logSubscriber.setRequestData(query.toString());
        logSubscriber.setStatus("Y");
        logSubscriber.setCreateTime(new Date());
        logSubscriber.setApiType("http");
        int logRe = tLogSubscriberMapper.insert(logSubscriber);
        if (logRe > 0) {
            log.info("增加请求记录表到 mysql成功...");

        }
//另外一张记录表
        TDataServiceResult dataServiceResult = new TDataServiceResult();
        dataServiceResult.setIdentityNo(logSubscriber.getId().toString());
        dataServiceResult.setChannelCode(channelCode);
        dataServiceResult.setChannelApiId(apiId);
        dataServiceResult.setJsonDetail(result1.toJSONString());
        dataServiceResult.setStatus("Y");
        int insert = tDataServiceResultMapper.insert(dataServiceResult);
        if (insert > 0) {
            log.info("增加查询ShipID json数据到mysql成功...");
            }
        resultMap.put("data", result1);
        return resultMap;
    }

你可能感兴趣的:(springboot)