场景:假设存在如下的表数据
student
name age sex course
fang 20 男 1
guo 20 女 2
course
id name
1 数学
2 语文这时从数据库中查询出来student之后,考虑到数据量比较大的情况下,不适合做连表查询,但是又需要知道学生选择的课程名,则可以使用ThreadLocal来缓存查询出来的课程对象,以减少数据库的访问量,如下:
public class CacheMapContext<K, V> {
private static final ThreadLocal<CacheMapContext> CACHE_CONTEXT_THREAD_LOCAL = new ThreadLocal<>();
private Map<K, V> cache;
public CacheMapContext() {
this.cache = new HashMap<>(10);
setContext(this);
}
private void setContext(CacheMapContext<K, V> context) {
CACHE_CONTEXT_THREAD_LOCAL.set(context);
}
public static <K, V> CacheMapContext<K, V> getInstance(Class<K> k, Class<V> v) {
return CACHE_CONTEXT_THREAD_LOCAL.get();
}
public void clean() {
CACHE_CONTEXT_THREAD_LOCAL.remove();
}
/**
* 获取缓存中的值
*
* @param k
* @return
*/
public V get(K k) {
return this.cache.get(k);
}
public void put(K k, V v) {
cache.put(k, v);
}
}使用:
@ResponseBody
@RequestMapping(value = "test")
public String test(TestConver testConver) {
//初始化缓存对象
CacheMapContext<Long, String> cache = new CacheMapContext();
//设置值
cache.put(1L, "111111111");
cache.put(2L, "222222222");
System.out.println(testConver);
get();
//清除缓存
cache.clean();
return testConver.toString();
}
public void get() {
System.out.println("get--->" + CacheMapContext.getInstance(Long.class, String.class).get(1L));
}类似这样, 当我们查询出数据之后,缓存到缓存对象中,当方法结束后,清除缓存对象,当课程id在之前查询过了时,就可以在缓存中命中了。
本文介绍了一种通过ThreadLocal缓存技术减少数据库访问次数的方法。适用于需要查询大量数据但又不想进行连表查询的场景,例如在获取学生及其所选课程名时的应用。
712

被折叠的 条评论
为什么被折叠?



