فهرست منبع

优化数据库敏感数据加解密缓存逻辑

woody 7 ماه پیش
والد
کامیت
5a75f40a03

+ 7 - 4
framework-database/src/main/java/com/chelvc/framework/database/context/CacheableDatabaseCryptoContext.java

@@ -18,7 +18,8 @@ import lombok.NonNull;
  * @date 2024/9/6
  */
 public class CacheableDatabaseCryptoContext extends DefaultDatabaseCryptoContext {
-    private final Cache<String, String> cache;
+    private final Cache<String, String> encrypts;
+    private final Cache<String, String> decrypts;
 
     public CacheableDatabaseCryptoContext(@NonNull DatabaseProperties properties) {
         super(properties);
@@ -26,7 +27,9 @@ public class CacheableDatabaseCryptoContext extends DefaultDatabaseCryptoContext
         int duration = properties.getSensitive().getCache().getDuration();
         AssertUtils.check(capacity > 0, () -> "capacity must be greater than 0");
         AssertUtils.check(duration > 0, () -> "duration must be greater than 0");
-        this.cache = Caffeine.newBuilder().maximumSize(capacity)
+        this.encrypts = Caffeine.newBuilder().maximumSize(capacity)
+                .expireAfterAccess(Duration.ofSeconds(duration)).build();
+        this.decrypts = Caffeine.newBuilder().maximumSize(capacity)
                 .expireAfterAccess(Duration.ofSeconds(duration)).build();
     }
 
@@ -35,7 +38,7 @@ public class CacheableDatabaseCryptoContext extends DefaultDatabaseCryptoContext
         if (StringUtils.isEmpty(plaintext)) {
             return plaintext;
         }
-        return this.cache.get(plaintext, k -> CodecUtils.encrypt(cipher, plaintext));
+        return this.encrypts.get(plaintext, k -> CodecUtils.encrypt(cipher, plaintext));
     }
 
     @Override
@@ -43,6 +46,6 @@ public class CacheableDatabaseCryptoContext extends DefaultDatabaseCryptoContext
         if (StringUtils.isEmpty(ciphertext)) {
             return ciphertext;
         }
-        return this.cache.get(ciphertext, k -> CodecUtils.decrypt(cipher, ciphertext));
+        return this.decrypts.get(ciphertext, k -> CodecUtils.decrypt(cipher, ciphertext));
     }
 }