cached-query 将缓存和查询数据库高速连接起来的轻类库

介绍

我们经常有这种需求:当我们把memcached增加到项目后我还还要写一个 cacheUtils 或者 cacheManager 之类的类来操作memcached。

而且一般的操作不外乎是这种操作:


  1. 拿到一段sql,先去memcahed里面看下是否有缓存,假设有就直接返回结果
  2. 假设没有就直接查询数据库
  3. 查到数据之后先保存到memcached里面再返回给上层调用者


这样的需求基本上占了缓存操作的大部分情况。这三件事情写起来非常easy,事实上还是有一些代码量的。cached-query 是一个轻量级的类库,帮你做了以上三件事情,而且仅仅提供一个方法就是通过sql查询得出一个列表。

安装

加入依赖到 pom.xml

<dependency>
  <groupId>org.crazycake</groupId>
  <artifactId>cached-query</artifactId>
  <version>1.0.0-RELEASE</version>
</dependency>


用法


建立一个配置文件 cached-query.properties  在classpath跟文件夹下,你能够放到 src/resources 下

#cache type. [memcached]
cache.type=memcached
cache.host=127.0.0.1
cache.port=11211
cache.expire=1800


建立你要查询的表相应的model

public class Student implements Serializable{
	private Integer studentId;
	private String studentName;
	public Integer getStudentId() {
		return studentId;
	}
	public void setStudentId(Integer studentId) {
		this.studentId = studentId;
	}
	public String getStudentName() {
		return studentName;
	}
	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}
	
}


在你的代码中使用它


CachedQuery q = CachedQuery.getInstance();
String sql="select student_id,student_name from student where student_id=?

"; Object[] params = new Object[]{1}; ArrayList<Student> list = q.queryList(sql, params, conn, Student.class);



注意事项

  • 要查询并被实例化的类一定要实现Serializable接口
  • 实例化的类里面属性的名字要取跟数据库里面字段相应的驼峰式命名。比方数据库中的字段是 student_name 相应的属性就是 studentName
  • 类的属性不能用基本类型。int要用Integer,float用Float,其它依次类推,事实上这样开发人员养成一个好习惯也是非常好的

最新版本号情况參考 https://github.com/alexxiyang/cached-query


原文地址:https://www.cnblogs.com/mfrbuaa/p/5418723.html