feat:sts缓存

pull/1121/head
梁宇奇 2025-03-28 13:56:52 +08:00
parent 708180cd90
commit 989d9ebe56
2 changed files with 34 additions and 2 deletions

View File

@ -1,7 +1,12 @@
package com.ruoyi.web.controller.common;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.oss.common.auth.Credentials;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.config.properties.OSSProperties;
import com.ruoyi.framework.oss.OSSClientWrapper;
import com.ruoyi.web.controller.common.vo.STSCredentialsVO;
@ -9,10 +14,13 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;
/**
*
*
@ -27,20 +35,39 @@ public class CommonController {
private OSSClientWrapper ossClient;
@Autowired
private OSSProperties ossProperties;
@Autowired
private RedisCache redisCache;
/**
* STS()
*/
@Value("${sts_cache_duration:1800}")
private Integer stsCacheDuration;
@ApiOperation("获取OSS临时访问凭证")
@GetMapping("/oss/getCredentials")
public R<STSCredentialsVO> getCredentials() {
STSCredentialsVO vo = new STSCredentialsVO();
Long currentUserId = SecurityUtils.getUserId();
if (currentUserId == null) {
return R.fail();
}
String cacheStr = redisCache.getCacheObject(CacheConstants.USER_STS_KEY + currentUserId);
if (StrUtil.isNotBlank(cacheStr)) {
//有缓存直接返回
return R.ok(JSONUtil.toBean(cacheStr, STSCredentialsVO.class));
}
Credentials credentials = ossClient.createStsCredentials();
STSCredentialsVO vo = new STSCredentialsVO();
vo.setAccessKeyId(credentials.getAccessKeyId());
vo.setAccessKeySecret(credentials.getSecretAccessKey());
vo.setSecurityToken(credentials.getSecurityToken());
vo.setBucketName(ossProperties.getBucketName());
vo.setRegionId(ossProperties.getRegionId());
vo.setEndPoint(ossProperties.getEndPoint());
vo.setExpiredDuration(ossProperties.getExpiredDuration());
vo.setExpiredDuration(ossProperties.getExpiredDuration() - stsCacheDuration);
vo.setHttpsFlag(ossProperties.isHttps());
//缓存
redisCache.setCacheObject(CacheConstants.USER_STS_KEY + currentUserId, JSONUtil.toJsonStr(vo),
stsCacheDuration, TimeUnit.SECONDS);
return R.ok(vo);
}

View File

@ -41,4 +41,9 @@ public class CacheConstants
* redis key
*/
public static final String PWD_ERR_CNT_KEY = "pwd_err_cnt:";
/**
* STS
*/
public static final String USER_STS_KEY = "user_sts:";
}