通俗的讲,服务器端缓存redis在项目中是作为一个DB在使用的,但是与DB不同的是它是以key,value方式存在的,而且它具有丰富的数据结构,redis将内存中的数据保持在磁盘中,配置好redis环境之后。
1.先写一个查询数据方法,代码如下:
/**
* Created by Robin 2017-08-18
*/
public class SearchDaoImp{
public List<Search> getAllByTitle(String pre) {
List<Search> list = new ArrayList<Search>();
Connection conn = null;
java.sql.PreparedStatement psq = null;
ResultSet rs = null;
try{
conn =DBUtil.Connect();
String sql = "select * from t_test where t_describe like '%"+pre+"%' or t_title like '%"+pre+"%'";
psq = conn.prepareStatement(sql);
System.out.println(sql);
rs = psq.executeQuery();
while(rs.next()){
Search s = new Search();
s.setId(rs.getInt(1));
s.setTitle(rs.getString(2));
s.setDescribe(rs.getString(3));
//list.add(s);
list.add(s);
}
}catch(SQLException e){
e.printStackTrace();
}finally{
try {
rs.close();
psq.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return list;
}
2.在业务层中,我们首先要清空缓存,再把从数据库中查出来的数据放入redis缓存中,代码如下
public class SearchServiceImp{
static SearchDaoImp searchDao = new SearchDaoImp();
String key = "";
//创建redis实例
static Jedis jedis = new Jedis("localhost");
//初始化缓存
public void init(){
jedis.flushDB();
}
//将数据存入缓存中
public List<String> putRedis(Search search){
List<String> list = null;
key = "id:"+search.getDescribe();
Map<String, String> map =new HashMap<String, String>();
List<Search> list1 = searchDao.getAllByTitle(search.getDescribe());
if(list1.size()>0){
for(Search s :list1){
map.put("title",s.getTitle());
map.put("describe", s.getDescribe());
// map.put("id", s.getId());
//注意:redis中的map数据结构,必须是String,String类型
}
jedis.hmset(key, map);//将map放入缓存中
list = jedis.hvals(key);//在缓存中根据key取出所有的值
}else{
//如果数据在数据库中没有被检索出来时,返回null
list = null;
}
return list;
}
}
3.数据放入redis缓存中,要从缓存中取出来,先要判断是否在缓存中有这条数据,然后在从缓存中取出来,代码如下:
//判断所要检索的对象是否在缓存中,是则从缓存中取
public boolean isExit(Search s){
String key = "id:"+s.getDescribe();
if(jedis.exists(key)){
return true;
}
else{
return false;
}
}
//将数据从缓存中取出来
public List<String> getRedis(Search search){
List<String> list = new ArrayList<String>();
String key = "id:"+search.getDescribe();
//在缓存中查找对应key值的value值
list = jedis.hmget(key,"title");
list.addAll(jedis.hmget(key, "describe"));
return list;
}
总结:redis还有 一些其他的方法,比如查询redis所有的key,设置redis中key的生存时间等等,在代码中我使用的是redis的map数据结构,除此之外,redis还有list、sort、set等等数据结构。