通过单例模式实现内存错误码缓存

This commit is contained in:
白茶清欢 2025-06-02 06:41:07 +08:00
parent a13c68f38d
commit a01dfaf671
4 changed files with 54 additions and 12 deletions

View File

@ -13,5 +13,13 @@
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,12 +0,0 @@
package cn.zhangdeman;
// 自定义异常的枚举值
public enum CustomExceptionEnum {
;
private final Object code; // 异常状态码
private final String message; // 异常信息
CustomExceptionEnum(Object code, String message) {
this.code = code;
this.message = message;
}
}

View File

@ -0,0 +1,32 @@
package cn.zhangdeman;
import java.util.HashMap;
import java.util.Map;
// 基于hashmap实现的内存缓存
// 因为就是服务启动时初始化一次, 无需考虑多线程并发安全问题
public class HashMapCache {
// 单例: 饿汉模式
private static final HashMapCache hashMapCache = new HashMapCache();
private final Map<Object, String> cache = new HashMap<>();
//将构造器设置为private禁止通过new进行实例化
private HashMapCache() {
}
public static HashMapCache getHashMapCache() {
return hashMapCache;
}
// 读取
public String getCodeMessage(Object code) {
if (!cache.containsKey(code)) {
// 不包含指定code
return code.toString();
}
return cache.get(code);
}
// 添加
public void put(Object code, String message) {
cache.put(code, message);
}
}

View File

@ -0,0 +1,14 @@
package cn.zhangdeman;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;
public class HashMapCacheTest {
@Test
public void runHashMapCache() {
HashMapCache.getHashMapCache().put(200, "OK");
Assert.assertEquals("OK", HashMapCache.getHashMapCache().getCodeMessage(200));
}
}