Introduced
We often have this demand: when we add memcached to the project, I also write a class like cacheutils or CacheManager to manipulate memcached. And the general operation is nothing more than this:
- Get a SQL, first go to memcahed inside to see if there is a cache, if there is a direct return to the results
- If not, query the database directly
- The data is saved to memcached and returned to the upper caller.
This requirement basically accounts for most of the cache operations. These three things are very simple to write, in fact, there is some amount of code. Cached-query is a lightweight class library that helps you do the above three things, and provides only one way to get a list from a SQL query.
Installation
Add dependency to Pom.xml
<dependency> <groupId>org.crazycake</groupId> <artifactid>cached-query</ Artifactid> <version>1.0.0-RELEASE</version></dependency>
How to use
Create a profile cached-query.properties in the Classpath directory, you can put it under src/resources.
#cache type. [memcached]cache.type=memcachedcache.host=127.0.0.1cache.port=11211cache.expire=1800
Create the model that corresponds to the table you want to query
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;}}
use it in your code
Cachedquery q = cachedquery.getinstance (); String sql= "Select Student_id,student_name from student where student_id=?"; O bject[] params = new Object[]{1}; arraylist<student> list = q.querylist (sql, params, conn, student.class);
Precautions
- The class to query and instantiate must implement the Serializable interface
- The name of the attribute inside the instantiated class is to take the hump-like name that corresponds to the field in the database, for example, the field in the database is student_name corresponding attribute is Studentname
- Class properties can not be used in the basic type, int to use integer,float with float, and so on, in fact, so developers develop a good habit is also very good
Latest Version Case reference Https://github.com/alexxiyang/cached-query
Cached-query Light class library that quickly connects cache and query databases