Solon 自定义Redis缓存存储-Solon论坛-开发交流-祥拓软件

Solon 自定义Redis缓存存储

  • 首先创建两个 interface 类
    • AppCache =》添加缓存
      @Target({ElementType.METHOD})
      @Retention(RetentionPolicy.RUNTIME)
      public @interface AppCache {
          String key() default "" ;
      }
    • AppCacheDelete =》删除缓存
      @Target({ElementType.METHOD})
      @Retention(RetentionPolicy.RUNTIME)
      public @interface AppCacheDelete {
      
          String key() default "" ;
      
      }
  • AOP 处理,应在 main 方法,solon启动后引入下列方法
    // 启动类
        public static void main(String[] args) {
            SolonApp app = Solon.start(WorkApp.class, args, solonApp -> {});
            addAppCache();
            deleteAppCache();
        }      
    
         public static void addAppCache() {
            Solon.context().beanAroundAdd(AppCache.class, inv->{
                AppCache cache = inv.method().getAnnotation(AppCache.class);
                String key = InvKeys.buildByTmlAndInv(cache.key(), inv);
                if (RedisTools.hasKey(key)) {
                    return RedisTools.getKey(key);
                }
                Object rst = inv.invoke();
                if (null != rst) {
                    RedisTools.setKey(key, rst);
                }
                return rst;
            });
        }
    
        public static void deleteAppCache() {
            Solon.context().beanAroundAdd(AppCacheDelete.class, inv->{
                AppCacheDelete cache = inv.method().getAnnotation(AppCacheDelete.class);
                String key = InvKeys.buildByTmlAndInv(cache.key(), inv);
                if (key.contains("*")) {
                    RedisTools.delList(key);
                } else {
                    RedisTools.del(key);
                }
                return inv.invoke();
            });
        }

    RedisTools 替换成自己的 redis 工具类

    // 查询 KEY 是否存在
    RedisTools.hasKey
    
    // 保存缓存
    RedisTools.setKey
    
    // 模糊删除
    RedisTools.delList
    
    // 根据 key 删除缓存
    RedisTools.del
  • 使用方法:在service的实现类的方法上引入  AppCache、AppCacheDelete,如下代码
    @Service
    public class TestServiceImpl implements TestService {
    
        @Override
        @SneakyThrows
        @AppCache(key = "此处为缓存的key,如 a 或 a:b:c 或 ${uuid} 或 a:${uuid} 或 a.b")
        public Map<String, Object> queryByUUID(String uuid) {
            return xxxx;
        }
    
    
        @Override
        @SneakyThrows
        @AppCacheDelete(key = "此处为缓存的key,如 a 或 a:b:c 或 ${uuid} 或 a:${uuid}:* 或 a.b")
        public Map<String, Object> queryByUUID(String uuid) {
            return xxxx;
        }
    
    }
请登录后发表评论

    请登录后查看回复内容