需求:需要对项目中部分接口实现过期,并且在接口过期之后不重启项目的情况下,让接口恢复访问
解决这个问题需要自定义一个拦截器
1.引入jar包
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
2.接口有效时间拦截器
package com.cnooc.config;
import cn.hutool.core.io.FileUtil;
import com.cnooc.constant.Constant;
import com.cnooc.util.AESExampleUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* 接口有效时间拦截器
* @Author: majinzhong
* @Data:2024/1/15
*/
@Component
@Slf4j
public class ApiValidTimeInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//获取过期时间戳
Long expirationTimestamp = this.getExpirationTimestamp(request);
//获取当前时间戳
long nowTime = System.currentTimeMillis();
if(expirationTimestamp<nowTime){
this.falseResult(response);
return false;
} else {
return true;
}
}
/**
* 获取过期时间
* @param request
* @return
*/
private Long getExpirationTimestamp(HttpServletRequest request){
try {
String filePath = "";
//判断是什么系统
boolean windows = FileUtil.isWindows();
if (windows) {
filePath = Constant.WINDOWS_PATH+"file/";
} else {
filePath = Constant.LINUX_PATH+"file/";
}
//获取这个文件夹下所有的文件
File[] ls = FileUtil.ls(filePath);
File file =null;
//如果为空就直接取规定好的文件
if (ls == null || ls.length == 0) {
file = new File(filePath+"licenses");
}else{
file = ls[0];
}
//获取文件中内容
String content = IOUtils.toString(file.toURI(), StandardCharsets.UTF_8);
if(StringUtils.isEmpty(content)) {
return Long.parseLong("0");
}else{
String decrypt = AESExampleUtil.decrypt(content);
return Long.parseLong(decrypt);
}
} catch (IOException e) {
e.printStackTrace();
return Long.parseLong("0");
}
}
/**
* 拦截后处理
*/
private void falseResult(HttpServletResponse response) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
response.getWriter().println("接口访问已经过期");
}
}
其中Constant.WINDOWS_PATH 和 Constant.LINUX_PATH是我自定义的文件上传路径
//windows上传文件路径
public static final String WINDOWS_PATH=System.getProperty("user.dir") + "/src/main/resources/";
//linux上传文件路径
public static final String LINUX_PATH="/home/upload/";
3.注册拦截器,设置拦截路径
package com.cnooc.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* 注册拦截器,设置拦截路径
* @Author: majinzhong
* @Data:2024/1/15
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
final ApiValidTimeInterceptor apiValidTimeInterceptor;
public WebMvcConfig(ApiValidTimeInterceptor apiValidTimeInterceptor) {
this.apiValidTimeInterceptor = apiValidTimeInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(apiValidTimeInterceptor)
.addPathPatterns("/api/**")
; //拦截路径
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
/** 配置knife4j 显示文档 */
registry.addResourceHandler("doc.html")
.addResourceLocations("classpath:/META-INF/resources/");
/**
* 配置swagger-ui显示文档
*/
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
/** 公共部分内容 */
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
配置了拦截器之后,swagger调用地址也需要进行配置,所以在拦截器中重写了addResourceHandlers方法
4.上传时间戳,不然ApiValidTimeInterceptor里面没有读取到licenses,也是会报错的
Controller类
@RestController
@RequestMapping("/licenses")
@Api(tags = "licenses上传接口",hidden=true)
public class LicensesController {
@Autowired
LicensesService licensesService;
@PostMapping("/upload")
@ApiOperation(value="licenses文件上传",notes="licenses文件上传接口")
@ApiImplicitParams({
@ApiImplicitParam(name="multipartFile",value="licenses文件",dataType="MultipartFile", paramType = "query",required = true),
})
@ApiResponse(response= WebResponse.class, code = 200, message = "接口返回对象参数")
public WebResponse uploadLicenses(@RequestParam MultipartFile multipartFile) {
return licensesService.uploadLicenses(multipartFile);
}
}
Service类
package com.cnooc.service.impl;
import cn.hutool.core.io.FileUtil;
import com.cnooc.constant.Constant;
import com.cnooc.response.WebResponse;
import com.cnooc.service.LicensesService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
/**
* @Author: majinzhong
* @Data:2024/1/16
*/
@Service
public class LicensesServiceImpl implements LicensesService {
@Override
public WebResponse uploadLicenses(MultipartFile multipartFile) {
String filePath = "";
//判断是什么系统
boolean windows = FileUtil.isWindows();
if (windows) {
filePath = Constant.WINDOWS_PATH+"file/";
} else {
filePath = Constant.LINUX_PATH+"file/";
}
//判断文件夹是否存在
boolean directory = FileUtil.isDirectory(filePath);
if (directory) {
//存在就清空文件夹
FileUtil.clean(filePath);
}else{
//不存在就创建
FileUtil.mkdir(filePath);
}
//获取文件全名称
String filename = multipartFile.getOriginalFilename();
//整理文件上唇路径
String rootFilePath = filePath + filename;
try {
multipartFile.transferTo(new File(new String(rootFilePath.getBytes(), "UTF-8")));
} catch (IOException e) {
e.printStackTrace();
return WebResponse.error(WebResponse.CODE_ERROE,"licenses文件上传失败!");
}
return WebResponse.success("licenses文件上传成功!");
}
}
5.因为ApiValidTimeInterceptor使用了解密时间戳的方式,所以也需要一个加密的工具类
package com.cnooc.util;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
/**
* @Author: majinzhong
* @Data:2024/1/15
*/
public class AESExampleUtil {
private static final String SECRET_KEY="axcfder78643jmil";
/**
* 加密
* @param data
* @return
*/
public static String encrypt(String data){
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8),"AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE,secretKeySpec);
byte[] bytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(bytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String decrypt(String data){
SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8),"AES");
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE,secretKeySpec);
byte[] decode = Base64.getDecoder().decode(data);
byte[] bytes = cipher.doFinal(decode);
return new String(bytes,StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String encrypt = encrypt("1737168846000");
System.out.println("加密后:"+encrypt);
String decrypt = decrypt(encrypt);
System.out.println("解密后:"+decrypt);
}
}
补充:因为之前项目中配置了解决前后端交互Long类型数据精度丢失问题的代码
//package com.cnooc.config;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.fasterxml.jackson.databind.module.SimpleModule;
//import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
//import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
///**
// * @Author majinzhong
// * @Date 2023/3/13 13:42
// * @Version 1.0
// * 统一注解,解决前后端交互Long类型精度丢失的问题
// */
//@Configuration
//public class JacksonConfig {
// /**
// * Jackson全局转化long类型为String,解决jackson序列化时传入前端Long类型缺失精度问题
// */
// @Bean
// public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
// Jackson2ObjectMapperBuilderCustomizer cunstomizer = new Jackson2ObjectMapperBuilderCustomizer() {
// @Override
// public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
// //将long类型变成字符串类型
// jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance);
// }
// };
// return cunstomizer;
// }
//}
在自定义拦截器之后就不起作用了,所以现在使用局部序列化器来解决Long类型精度丢失的问题
package com.cnooc.util;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
/**
* 局部设置一个序列化器,在哪使用哪添加
* @Author: majinzhong
* @Data:2024/1/16
*/
public class Long2StringSerialize extends JsonSerializer<Long> {
@Override
public void serialize(Long aLong, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
//aLong就是原始的数据
if (aLong!=null){
jsonGenerator.writeString(aLong.toString());
}
}
}
需要在哪里使用这个序列化器,就在那里引用@JsonSerialize(using = Long2StringSerialize.class)
至此,完结,撒花