通过单例模式实现内存错误码缓存
This commit is contained in:
parent
a13c68f38d
commit
a01dfaf671
8
pom.xml
8
pom.xml
@ -13,5 +13,13 @@
|
|||||||
<maven.compiler.target>21</maven.compiler.target>
|
<maven.compiler.target>21</maven.compiler.target>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
</properties>
|
</properties>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>4.13.2</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
32
src/main/java/cn/zhangdeman/HashMapCache.java
Normal file
32
src/main/java/cn/zhangdeman/HashMapCache.java
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
14
src/test/java/cn/zhangdeman/HashMapCacheTest.java
Normal file
14
src/test/java/cn/zhangdeman/HashMapCacheTest.java
Normal 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));
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user