cached-query

jopen 10年前

介绍

我们常常有这样的需求:当我们把memcached加入到项目后我还还要写一个 cacheUtils 或者 cacheManager 之类的类来操作memcached。并且一般的操作不外乎是这种操作:

  1. 拿到一段sql,先去memcahed里面看下是否有缓存,如果有就直接返回结果

  2. 如果没有就直接查询数据库

  3. 查到数据之后先保存到memcached里面再返回给上层调用者

这种需求基本上占了缓存操作的大部分情况。这三件事情写起来很简单,其实还是有一些代码量的。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,其他依次类推,其实这样开发者养成一个好习惯也是很好的

项目主页:http://www.open-open.com/lib/view/home/1411218274421