‹
定时任务+邮件发送+OSS
@Scheduled(cron = "${precache.recommend.cron}")
public void doPreCache() {
RLock lock = redissonClient.getLock(LOCK_KEY);
try {
// wait=0 抢不到直接放弃,lease=-1 启用看门狗续锁
boolean ok = lock.tryLock(0, -1, TimeUnit.MILLISECONDS);
if (!ok) {
log.info("推荐预热任务: 抢锁失败, 其他实例正在执行");
return;
}
log.info("推荐预热任务: 获取锁成功, 开始执行");
List<User> userList = userService.list();
for (User user : userList) {
Long userId = user.getId();
try {
List<User> recList = recommendService.getRecommendList(userId, 20);
if (recList == null || recList.isEmpty()) continue;
String key = "yupao:user:recommend:" + userId;
valueOperations.set(key, recList, cacheTtl, TimeUnit.SECONDS);
} catch (Exception e) {
log.error("userId {} 缓存写入失败", userId, e);
}
}
log.info("推荐预热任务: 执行完成");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("推荐预热任务被中断", e);
} catch (Exception e) {
log.error("推荐预热任务全局异常", e);
} finally {
if (lock.isHeldByCurrentThread()) { // 安全解锁:只释放自己持有的锁
lock.unlock();
}
}
}
@Service
public class MailService {
@Autowired
private JavaMailSender mailSender;
private static final String AUTHOR_NAME = "author";
private static final String SENDER = "15779544219@163.com";
public void sendHtmlMail(String to, String subject, String htmlContent) {
try {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setFrom(AUTHOR_NAME + "<" + SENDER + ">");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(htmlContent, true); // true = 发送 HTML 格式
mailSender.send(mimeMessage);
} catch (MessagingException e) {
throw new RuntimeException("邮件发送失败", e);
}
}
}
// 准备阿里云信息
endpoint --> oss 服务地址
access-key-id --> 访问密钥 ID
access-key-secret --> 访问密钥 Secret
bucket-name --> bucket 名称
--> 对于前端 建议设置关联自己的域名 从而确保前端直接显示对应的内容(图片等) 而避免弹出下载
--> 访问控制: 授权主体(创建用户) 授权策略(OSS)
// 域名管理
绑定自定义域名
先填写一个准备要绑定的域名, 自动校验主域名
创建TXT记录域名_dnsauth.要绑定的子域名
创建CNAME记录域名要绑定的子域名
Tip: 创建解析不要多写主域名
// application.yml 对应的配置数据
aliyun:
oss:
endpoint: ${OSS_ENDPOINT}
access-key-id: ${OSS_ACCESS_KEY_ID}
access-key-secret: ${OSS_ACCESS_KEY_SECRET}
bucket: ${OSS_BUCKET}
// 配置类 从 application.yml 读取配置数据
@Configuration
public class OssConfig {
@Value("${aliyun.oss.endpoint}")
private String endpoint;
@Value("${aliyun.oss.access-key-id}")
private String accessKeyId;
@Value("${aliyun.oss.access-key-secret}")
private String accessKeySecret;
@Bean(destroyMethod = "shutdown")
public OSS ossClient() {
return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
}
}
@Service
public class OssService {
private final OSS ossClient;
private final String bucket;
public OssService(OSS ossClient, @Value("${aliyun.oss.bucket}") String bucket) {
this.ossClient = ossClient;
this.bucket = bucket;
}
// 普通上传
public String upload(MultipartFile file) throws IOException {
if (file.isEmpty()) {
throw new IllegalArgumentException("文件不能为空");
}
String objectKey = UUID.randomUUID() + "-" + file.getOriginalFilename();
ossClient.putObject(bucket, objectKey, file.getInputStream());
return objectKey;
}
// 指定文件夹上传(把文件上传到指定目录,例如:avatar/xxx.jpg)
public String uploadToFolder(MultipartFile file, String folderPath) throws IOException {
if (file.isEmpty()) {
throw new IllegalArgumentException("文件不能为空");
}
// folderPath 要求以 / 结尾,比如 "avatar/"
if (!folderPath.endsWith("/")) {
folderPath = folderPath + "/";
}
String objectKey = folderPath + UUID.randomUUID() + "-" + file.getOriginalFilename();
ossClient.putObject(bucket, objectKey, file.getInputStream());
return objectKey;
}
// 创建模拟文件夹
public void createFolder(String folderPath) {
// 必须以 / 结尾
if (!folderPath.endsWith("/")) {
folderPath = folderPath + "/";
}
ossClient.putObject(bucket, folderPath, "".getBytes());
}
// 递归删除文件夹(目录下所有文件+子目录全部删掉)
public void deleteFolder(String folderPath) {
if (!folderPath.endsWith("/")) {
folderPath = folderPath + "/";
}
ListObjectsV2Request req = new ListObjectsV2Request()
.withBucketName(bucket)
.withPrefix(folderPath)
.withMaxKeys(1000);
ListObjectsV2Result result;
do {
result = ossClient.listObjectsV2(req);
for (OSSObjectSummary summary : result.getObjectSummaries()) {
ossClient.deleteObject(bucket, summary.getKey());
}
req.setContinuationToken(result.getNextContinuationToken());
} while (result.isTruncated());
}
// 列出文件夹下所有文件(只当前层级,不递归子目录)
public List<String> listFileInFolder(String folderPath) {
if (!folderPath.endsWith("/")) {
folderPath = folderPath + "/";
}
List<String> keyList = new ArrayList<>();
ListObjectsV2Request req = new ListObjectsV2Request()
.withBucketName(bucket)
.withPrefix(folderPath)
.withDelimiter("/") // 加delimiter,实现只看当前层,子文件夹作为commonPrefix
.withMaxKeys(1000);
ListObjectsV2Result result;
do {
result = ossClient.listObjectsV2(req);
for (OSSObjectSummary summary : result.getObjectSummaries()) {
keyList.add(summary.getKey());
}
req.setContinuationToken(result.getNextContinuationToken());
} while (result.isTruncated());
return keyList;
}
// 列出子文件夹(当前目录下的子文件夹)
public List<String> listSubFolder(String folderPath) {
if (!folderPath.endsWith("/")) {
folderPath = folderPath + "/";
}
List<String> subFolderList = new ArrayList<>();
ListObjectsV2Request req = new ListObjectsV2Request()
.withBucketName(bucket)
.withPrefix(folderPath)
.withDelimiter("/")
.withMaxKeys(1000);
ListObjectsV2Result result;
do {
result = ossClient.listObjectsV2(req);
subFolderList.addAll(result.getCommonPrefixes());
req.setContinuationToken(result.getNextContinuationToken());
} while (result.isTruncated());
return subFolderList;
}
// 预览 -- 临时访问链接 -- 有效期
public String generatePresignedUrl(String objectKey, long expireSeconds) {
Date expireDate = new Date(System.currentTimeMillis() + expireSeconds * 1000);
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucket, objectKey);
request.setExpiration(expireDate);
URL url = ossClient.generatePresignedUrl(request);
return url.toString();
}
// 下载
public InputStream download(String objectKey) {
OSSObject object = ossClient.getObject(bucket, objectKey);
return object.getObjectContent();
}
// 删除单个文件
public void delete(String objectKey) {
ossClient.deleteObject(bucket, objectKey);
}
}
// Controller
@RestController
@RequestMapping("/files")
public class FileController {
private final OssService ossService;
public FileController(OssService ossService) {
this.ossService = ossService;
}
// 普通上传
@PostMapping
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
return ossService.upload(file);
}
// 上传到指定文件夹
@PostMapping("/folder-upload")
public String uploadToFolder(@RequestParam("file") MultipartFile file,
@RequestParam("folderPath") String folderPath) throws IOException {
return ossService.uploadToFolder(file, folderPath);
}
// 创建文件夹
@PostMapping("/folder")
public void createFolder(@RequestParam("folderPath") String folderPath) {
ossService.createFolder(folderPath);
}
// 删除文件夹(递归清空)
@DeleteMapping("/folder")
public void deleteFolder(@RequestParam("folderPath") String folderPath) {
ossService.deleteFolder(folderPath);
}
// 查询文件夹内文件列表
@GetMapping("/folder/files")
public List<String> listFile(@RequestParam("folderPath") String folderPath) {
return ossService.listFileInFolder(folderPath);
}
// 查询文件夹下子文件夹
@GetMapping("/folder/sub")
public List<String> listSubFolder(@RequestParam("folderPath") String folderPath) {
return ossService.listSubFolder(folderPath);
}
// 预览
@GetMapping("/presigned-url")
public String getPresignedUrl(@RequestParam String objectKey,
@RequestParam(defaultValue = "1800") long expireSeconds) {
return ossService.generatePresignedUrl(objectKey, expireSeconds);
}
// 下载
@GetMapping("/download")
public void download(@RequestParam String objectKey, HttpServletResponse response) throws IOException {
try (InputStream input = ossService.download(objectKey)) {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"download\"");
input.transferTo(response.getOutputStream());
}
}
// 删除单个文件
@DeleteMapping
public void delete(@RequestParam String objectKey) {
ossService.delete(objectKey);
}
}
/*
上传注意文件大小限制
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB
*/