最近公司项目出现这样一个问题,公司的项目部署在政务云服务器,而政务云服务器所在网络是电信提供的,如果用户通过手机的非电信4G网络访问项目资源,比如MP4等,则会被电信拦截,导致访问极慢无法正常提供服务。为了解决这个问题需要用cdn服务来提供资源,以前的资源都是存在服务器上,因此需要做最小的调整切换cdn服务。
解决方案:
在spring框架下,可以利用ResponseBodyAdvice接口,实现该接口则能够在声明了ResponseBody注解的controller返回json数据前,统一对json数据做处理,将资源地址的url统一替换为cdn资源url。
源码下载(包括注解类等完整java类):https://download.csdn.net/download/wy277737174/10916038
源码参考:
@ControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice{
protected Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public Object beforeBodyWrite(Object returnValue, MethodParameter arg1, MediaType arg2, Class arg3, ServerHttpRequest arg4,
ServerHttpResponse arg5) {
if(returnValue instanceof JsonResultUtil) {
try {
JsonResultUtil msg=(JsonResultUtil) returnValue;
if(msg.get("data") instanceof ArrayList) {
logger.info("MyResponseBodyAdvice getTypeName-->" + msg.get("data").getClass().getTypeName());
String data = new Gson().toJson(msg.get("data"));
if(data.contains("http://znx.****.com")) {
Gson gson1=new Gson();
logger.info("msg.get(\"data\").getClass().getTypeName()-->" + msg.get("data").getClass().getTypeName());
List list= gson1.fromJson(data.replaceAll("http://znx.****.com", "http://znxcdn.****.com"), new TypeToken() {}.getType());
msg.put("data", list);
}
}else if(msg.containsKey("data") && msg.get("data") != null) {
logger.info("MyResponseBodyAdvice getTypeName-->" + msg.get("data").getClass().getTypeName());
String data = new Gson().toJson(msg.get("data"));
String className = msg.get("data").getClass().getTypeName();
Class pClass=Class.forName(className);
//构造器
Constructor c= pClass.getConstructor();
//通过构造器实例化
Object obj = c.newInstance();
if(data.contains("http://znx.*****.com")) {
Gson gson1=new Gson();
logger.info("msg.get(\"data\").getClass().getTypeName()-->" + msg.get("data").getClass().getTypeName());
obj = gson1.fromJson(data.replaceAll("http://znx.****.com", "http://znxcdn.****.com"), obj.getClass());
msg.put("data", obj);
}
}
}catch(Exception e) {
e.printStackTrace();
logger.info("MyResponseBodyAdvice 出错-->" + e.getMessage());
}
}
logger.info("MyResponseBodyAdvice-->" + new Gson().toJson(returnValue));
//统一修改返回值/响应体
//返回修改后的值
return returnValue;
}
@Override
public boolean supports(MethodParameter arg0, Class arg1) {
NeedEditResponseBody anno = arg0.getMethod().getAnnotation(NeedEditResponseBody.class);
logger.info("NeedEditResponseBody --->" + anno);
if(anno != null) { //只有方法上有NeedEditResponseBody,才会对json数据进行再处理,将资源改为cdn资源
return true;
}
return false;
}
}
(转载本站原创文章请注明作者与出处Coding云--codingyun.com)





