Redis缓存操作

文件下载需要保存临时变量

静态常量,在com.swx.easypan.entity.constants包下的 Constants 类中定义常量

public class Constants {
public static final String REDIS_KEY_DOWNLOAD = "easypan:download:";
}

从Redis缓存中获取和保存文件下载信息,在RedisComponent 编写获取和保存方法。

RedisComponent
@Component("redisComponent")
public class RedisComponent {

@Resource
private RedisUtils<Object> redisUtils;

// 保存下载文件信息
public void saveDownloadCode(String code, DownloadFileDTO fileDTO) {
redisUtils.setex(Constants.REDIS_KEY_DOWNLOAD + code, fileDTO, Constants.REDIS_KEY_EXPIRE_FIVE_MIN);
}

// 获取下载文件信息
public DownloadFileDTO getDownloadCode(String code) {
return (DownloadFileDTO) redisUtils.get(Constants.REDIS_KEY_DOWNLOAD + code);
}
}

创建下载链接

为了防止链接被无限使用,自己创建下载链接,附带code参数,控制链接有效性。

接口信息

路径地址 http://localhost:7090/api/file/createDownloadUrl/{id}
请求方式 GET
请求参数 id
返回结果 Map<String, String>

定义Service

找到 FileInfoService,定义文件重命名方法

FileInfoService
/**
* 创建下载链接
*
* @param userId 用户ID
* @param id 文件ID
*/
String createDownloadUrl(String userId, String id);

在 FileInfoServiceImpl 中,实现上述方法

FileInfoServiceImpl
/**
* 创建下载链接
*
* @param userId 用户ID
* @param id 文件ID
*/
@Override
public String createDownloadUrl(String userId, String id) {
// 防小人
FileInfo fileInfo = getByMultiId(id, userId);
if (fileInfo == null) {
throw new BizException(ResultCode.PARAM_IS_INVALID);
}
if (FileFolderTypeEnums.FOLDER.getType().equals(fileInfo.getFolderType())) {
throw new BizException(ResultCode.PARAM_IS_INVALID);
}
String code = StringTools.getRandomString(Constants.LENGTH_50);
DownloadFileDTO fileDTO = new DownloadFileDTO();
fileDTO.setCode(code);
fileDTO.setFilename(fileInfo.getFilename());
fileDTO.setFilePath(fileInfo.getFilePath());
// 保存到Redis
redisComponent.saveDownloadCode(code, fileDTO);
return code;
}

定义Controller

在 FileInfoController 下定义文件重命名方法。

FileInfoController
// 创建下载链接
@GetMapping("/createDownloadUrl/{id}")
public Map<String, String> createDownloadUrl(HttpSession session, @PathVariable("id") @NotEmpty String id) {
SessionWebUserVO user = (SessionWebUserVO) session.getAttribute(Constants.SESSION_KEY);
// 需要校验登陆状态
String code = fileInfoService.createDownloadUrl(user.getId(), id);
HashMap<String, String> data = new HashMap<>();
data.put("code", code);
return data;
}

下载文件

接口信息

路径地址 http://localhost:7090/api/file/download/{code}
请求方式 GET
请求参数 code
返回结果 字节流

定义Controller

在 FileInfoController 下定义下载文件方法。根据code从Redis中获取文件信息,然后以字节流的形式返回给前端。

FileInfoController
// 下载文件,无需登陆
@LoginValidator(validated = false)
@GetMapping("/download/{code}")
public void download(HttpServletRequest request,
HttpServletResponse response,
@PathVariable @NotEmpty String code) throws UnsupportedEncodingException {
DownloadFileDTO fileDTO = redisComponent.getDownloadCode(code);
if (null == fileDTO) {
return;
}
String filePath = appConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + fileDTO.getFilePath();
String filename = fileDTO.getFilename();
FileUtils.writeDownloadFile(response, request, filename, filePath);
}