Просмотр исходного кода

feat:后端项目切换缓存方案,从redis切换到caffeine,cache目前只缓存用户的登陆信息

yang yi 11 месяцев назад
Родитель
Сommit
00c9ff7ce4

+ 4 - 4
pom.xml

@@ -63,10 +63,6 @@
             <artifactId>jjwt</artifactId>
             <version>0.9.1</version>
         </dependency>
-        <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-starter-data-redis</artifactId>
-        </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-validation</artifactId>
@@ -75,6 +71,10 @@
             <groupId>org.projectlombok</groupId>
             <artifactId>lombok</artifactId>
         </dependency>
+        <dependency>
+            <groupId>com.github.ben-manes.caffeine</groupId>
+            <artifactId>caffeine</artifactId>
+        </dependency>
     </dependencies>
 
 </project>

+ 27 - 0
src/main/java/space/anyi/openAPI/config/CaffeineConfig.java

@@ -0,0 +1,27 @@
+package space.anyi.openAPI.config;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import org.springframework.boot.autoconfigure.cache.CacheProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @ProjectName: yangyi-open-api-platform
+ * @FileName: CaffeineConfig
+ * @Author: 杨逸
+ * @Data:2025/10/16 8:38
+ * @Description: 本地缓存配置
+ */
+@Configuration
+public class CaffeineConfig {
+    @Bean("localCache")
+    public Cache<String, Object> cache(){
+        return Caffeine.newBuilder()
+                .initialCapacity(100)
+                .maximumSize(1000)
+                .expireAfterWrite(1, TimeUnit.DAYS).build();
+    }
+}

+ 9 - 6
src/main/java/space/anyi/openAPI/filter/JWTAuthenticationTokenFilter.java

@@ -2,6 +2,7 @@ package space.anyi.openAPI.filter;
 
 
 import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.benmanes.caffeine.cache.Cache;
 import io.jsonwebtoken.Claims;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -14,10 +15,7 @@ import org.springframework.web.filter.OncePerRequestFilter;
 import space.anyi.openAPI.constant.SystemConstants;
 import space.anyi.openAPI.model.ResponseResult;
 import space.anyi.openAPI.model.user.LoginUserDetails;
-import space.anyi.openAPI.model.user.User;
-import space.anyi.openAPI.service.UserService;
 import space.anyi.openAPI.util.JwtUtil;
-import space.anyi.openAPI.util.RedisCache;
 import space.anyi.openAPI.util.WebUtils;
 
 import javax.annotation.Resource;
@@ -39,7 +37,7 @@ import java.util.Objects;
 public class JWTAuthenticationTokenFilter extends OncePerRequestFilter {
     private final static Logger log = LoggerFactory.getLogger(JWTAuthenticationTokenFilter.class);
     @Resource
-    private RedisCache redisCache;
+    private Cache localCache;
     @Resource
     private ObjectMapper objectMapper;
 
@@ -65,8 +63,13 @@ public class JWTAuthenticationTokenFilter extends OncePerRequestFilter {
             WebUtils.renderString(httpServletResponse, objectMapper.writeValueAsString(errorResult));
             return;
         }
-        //从redis中获取用户信息
-        LoginUserDetails loginUserDetails = redisCache.getCacheObject(SystemConstants.LOGIN_USER_REDIS_KEY +jwt.getSubject());
+        //从缓存中获取用户信息
+        Object cacheMsg = localCache.get(SystemConstants.LOGIN_USER_REDIS_KEY + jwt.getSubject(), key -> null);
+        LoginUserDetails loginUserDetails  =null;
+        if (Objects.nonNull(cacheMsg)) {
+            loginUserDetails = (LoginUserDetails) cacheMsg;
+        }
+
 
         //已退出登陆或登陆已过期
         if(Objects.isNull(loginUserDetails)){

+ 0 - 2
src/main/java/space/anyi/openAPI/model/user/dto/RequestRegisterUser.java

@@ -1,7 +1,5 @@
 package space.anyi.openAPI.model.user.dto;
 
-import com.baomidou.mybatisplus.annotation.IdType;
-import com.baomidou.mybatisplus.annotation.TableId;
 import io.swagger.annotations.ApiModel;
 import io.swagger.annotations.ApiModelProperty;
 import lombok.Data;

+ 5 - 4
src/main/java/space/anyi/openAPI/service/impl/UserServiceImpl.java

@@ -5,6 +5,7 @@ import cn.hutool.core.util.IdUtil;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.github.benmanes.caffeine.cache.Cache;
 import org.springframework.security.authentication.AuthenticationManager;
 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
 import org.springframework.security.core.Authentication;
@@ -24,7 +25,6 @@ import space.anyi.openAPI.model.user.vo.UserVO;
 import space.anyi.openAPI.service.UserService;
 import space.anyi.openAPI.util.BeanCopyUtil;
 import space.anyi.openAPI.util.JwtUtil;
-import space.anyi.openAPI.util.RedisCache;
 
 import javax.annotation.Resource;
 import java.util.*;
@@ -39,7 +39,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
     @Resource
     private  AuthenticationManager authenticationManager;
     @Resource
-    private RedisCache redisCache;
+    private Cache<String,Object> localCache;
     @Resource
     private  PasswordEncoder passwordEncoder;
     @Override
@@ -55,8 +55,9 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
         Long id = principal.getUser().getId();
         String jwt = JwtUtil.createJWT(id.toString());
         //todo:权限
-        //存入redis
-        redisCache.setCacheObject(SystemConstants.LOGIN_USER_REDIS_KEY+id,principal);
+        //存入缓存
+        localCache.put(SystemConstants.LOGIN_USER_REDIS_KEY+id,principal);
+        //redisCache.setCacheObject(SystemConstants.LOGIN_USER_REDIS_KEY+id,principal);
         //返回结果
         Map<String,Object> map = new HashMap<>();
         UserInfo userInfo = new UserInfo(principal.getUser().getUserAccount(),principal.getUser().getUserName(),principal.getUser().getUserAvatar(),principal.getUser().getUserRole());

+ 0 - 252
src/main/java/space/anyi/openAPI/util/RedisCache.java

@@ -1,252 +0,0 @@
-package space.anyi.openAPI.util;
-
-import org.springframework.data.redis.core.BoundSetOperations;
-import org.springframework.data.redis.core.HashOperations;
-import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.data.redis.core.ValueOperations;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.Resource;
-import java.util.*;
-import java.util.concurrent.TimeUnit;
-
-/**
- * @ProjectName: BI
- * @FileName: RedisCache
- * @Author: 杨逸
- * @Data:2024/11/28 20:05
- * @Description:
- */
-@Component
-public class RedisCache {
-    @Resource
-    public RedisTemplate redisTemplate;
-
-    /**
-     * 缓存基本的对象,Integer、String、实体类等
-     *
-     * @param key 缓存的键值
-     * @param value 缓存的值
-     */
-    public <T> void setCacheObject(final String key, final T value)
-    {
-        redisTemplate.opsForValue().set(key, value);
-    }
-
-    /**
-     * 缓存基本的对象,Integer、String、实体类等
-     *
-     * @param key 缓存的键值
-     * @param value 缓存的值
-     * @param timeout 时间
-     * @param timeUnit 时间颗粒度
-     */
-    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
-    {
-        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
-    }
-
-    /**
-     * 设置有效时间
-     *
-     * @param key Redis键
-     * @param timeout 超时时间
-     * @return true=设置成功;false=设置失败
-     */
-    public boolean expire(final String key, final long timeout)
-    {
-        return expire(key, timeout, TimeUnit.SECONDS);
-    }
-
-    /**
-     * 设置有效时间
-     *
-     * @param key Redis键
-     * @param timeout 超时时间
-     * @param unit 时间单位
-     * @return true=设置成功;false=设置失败
-     */
-    public boolean expire(final String key, final long timeout, final TimeUnit unit)
-    {
-        return redisTemplate.expire(key, timeout, unit);
-    }
-
-    /**
-     * 获得缓存的基本对象。
-     *
-     * @param key 缓存键值
-     * @return 缓存键值对应的数据
-     */
-    public <T> T getCacheObject(final String key)
-    {
-        ValueOperations<String, T> operation = redisTemplate.opsForValue();
-        return operation.get(key);
-    }
-
-    /**
-     * 删除单个对象
-     *
-     * @param key
-     */
-    public boolean deleteObject(final String key)
-    {
-        return redisTemplate.delete(key);
-    }
-
-    /**
-     * 删除集合对象
-     *
-     * @param collection 多个对象
-     * @return
-     */
-    public long deleteObject(final Collection collection)
-    {
-        return redisTemplate.delete(collection);
-    }
-
-    /**
-     * 缓存List数据
-     *
-     * @param key 缓存的键值
-     * @param dataList 待缓存的List数据
-     * @return 缓存的对象
-     */
-    public <T> long setCacheList(final String key, final List<T> dataList)
-    {
-        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
-        return count == null ? 0 : count;
-    }
-
-    /**
-     * 获得缓存的list对象
-     *
-     * @param key 缓存的键值
-     * @return 缓存键值对应的数据
-     */
-    public <T> List<T> getCacheList(final String key)
-    {
-        return redisTemplate.opsForList().range(key, 0, -1);
-    }
-
-    /**
-     * 缓存Set
-     *
-     * @param key 缓存键值
-     * @param dataSet 缓存的数据
-     * @return 缓存数据的对象
-     */
-    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet)
-    {
-        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
-        Iterator<T> it = dataSet.iterator();
-        while (it.hasNext())
-        {
-            setOperation.add(it.next());
-        }
-        return setOperation;
-    }
-
-    /**
-     * 获得缓存的set
-     *
-     * @param key
-     * @return
-     */
-    public <T> Set<T> getCacheSet(final String key)
-    {
-        return redisTemplate.opsForSet().members(key);
-    }
-
-    /**
-     * 缓存Map
-     *
-     * @param key
-     * @param dataMap
-     */
-    public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
-    {
-        if (dataMap != null) {
-            redisTemplate.opsForHash().putAll(key, dataMap);
-        }
-    }
-
-    /**
-     * 获得缓存的Map
-     *
-     * @param key
-     * @return
-     */
-    public <T> Map<String, T> getCacheMap(final String key)
-    {
-        return redisTemplate.opsForHash().entries(key);
-    }
-
-    /**
-     * 往Hash中存入数据
-     *
-     * @param key Redis键
-     * @param hKey Hash键
-     * @param value 值
-     */
-    public <T> void setCacheMapValue(final String key, final String hKey, final T value)
-    {
-        redisTemplate.opsForHash().put(key, hKey, value);
-    }
-
-    /**
-     * 自增map中的值
-     * @param key map的key
-     * @param hKey map中的key
-     */
-    public void incrementCacheMapValue(final String key,final String hKey){
-        redisTemplate.opsForHash().increment(key,hKey,1);
-    }
-
-    /**
-     * 获取Hash中的数据
-     *
-     * @param key Redis键
-     * @param hKey Hash键
-     * @return Hash中的对象
-     */
-    public <T> T getCacheMapValue(final String key, final String hKey)
-    {
-        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
-        return opsForHash.get(key, hKey);
-    }
-
-    /**
-     * 删除Hash中的数据
-     *
-     * @param key
-     * @param hkey
-     */
-    public void delCacheMapValue(final String key, final String hkey)
-    {
-        HashOperations hashOperations = redisTemplate.opsForHash();
-        hashOperations.delete(key, hkey);
-    }
-
-    /**
-     * 获取多个Hash中的数据
-     *
-     * @param key Redis键
-     * @param hKeys Hash键集合
-     * @return Hash对象集合
-     */
-    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
-    {
-        return redisTemplate.opsForHash().multiGet(key, hKeys);
-    }
-
-    /**
-     * 获得缓存的基本对象列表
-     *
-     * @param pattern 字符串前缀
-     * @return 对象列表
-     */
-    public Collection<String> keys(final String pattern)
-    {
-        return redisTemplate.keys(pattern);
-    }
-}

+ 0 - 4
src/main/resources/application.yaml

@@ -8,10 +8,6 @@ spring:
     username: root
     password: hsp
     url: jdbc:mysql://localhost:3306/open_api_platform?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
-  redis:
-    database: 0
-    host: localhost
-    port: 6379
   mvc:
     pathmatch:
       matching-strategy: ant_path_matcher

+ 28 - 0
src/test/java/space/anyi/openAPI/config/CaffeineConfigTest.java

@@ -0,0 +1,28 @@
+package space.anyi.openAPI.config;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import lombok.extern.slf4j.Slf4j;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * @ProjectName: yangyi-open-api-platform
+ * @FileName: CaffeineConfigTest
+ * @Author: 杨逸
+ * @Data:2025/10/16 8:44
+ * @Description: 测试本地缓存caffeine
+ */
+@SpringBootTest
+class CaffeineConfigTest {
+    @Autowired
+    private Cache<String, Object> localCache;
+
+    @Test
+    void cache() {
+        localCache.put("test", "test");
+        assertEquals("test", localCache.getIfPresent("test"));
+    }
+}