使用Redis缓存同步,从缓存中存取数据的一些使用

来源:互联网 发布:nba新浪数据库 编辑:程序博客网 时间:2024/06/05 15:59

关于Redis的安装本篇不作介绍

Redis主要用于缓存(数据查询,短连接,商品内容等),应用排行榜,访问统计等..
Redis常用数据类型
Redis最为常用的数据类型主要有以下五种:

String
Hash
List
Set
Sorted set

Redis配置文件redis.properties:
redis.maxIdle=30
redis.minIdle=10
redis.maxTotal=100
redis.url=此处为redis所在服务器的URL
redis.port=6379 //默认是6379端口

自己封装一个JedisUtils来连接redis

public class JedisUtils {    private static JedisPool jedisPool=null;    static{        //加载配置文件        InputStream in=JedisUtils.class.getClassLoader().getResourceAsStream("redis.properties");        Properties pro=new Properties();        try {            pro.load(in);        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        //创建池子的配置对象        JedisPoolConfig poolConfig=new JedisPoolConfig();        //最大连接数        poolConfig.setMaxTotal(Integer.parseInt(pro.get("redis.maxIdle").toString()));        //最大空闲连接数        poolConfig.setMaxIdle(Integer.parseInt(pro.get("redis.minIdle").toString()));        //最小空闲连接数        poolConfig.setMinIdle(Integer.parseInt(pro.get("redis.maxTotal").toString()));        //创建连接池       jedisPool=new JedisPool(poolConfig, pro.get("redis.url").toString(),Integer.parseInt(pro.get("redis.port").toString()));    }    //获得jedis资源    public static Jedis getJedis() {        return jedisPool.getResource();    }

例如:在查询内容时使用

    public List<TbContent> getContentListByCid(long cid) {        //从缓存中读取        try {            Jedis jedis=JedisUtils.getJedis();            String json=jedis.hget(CONTENT_LIST, cid+"");            if (!(json.isEmpty())) {                List<TbContent> list = JsonUtils.jsonToList(json, TbContent.class);                return list;            }        } catch (Exception e) {            // TODO: handle exception        }        TbContentExample example = new TbContentExample();        Criteria criteria = example.createCriteria();        //设置查询条件        criteria.andCategoryIdEqualTo(cid);        //执行查询        List<TbContent> list = contentMapper.selectByExampleWithBLOBs(example);        //写入缓存        try {            Jedis jedis=JedisUtils.getJedis();            jedis.hset(CONTENT_LIST,cid + "", JsonUtils.objectToJson(list));        } catch (Exception e) {            // TODO: handle exception        }        return list;    }

先去查询缓存中是否存在CONTENT_LIST键,有就拿到对应的值直接返回,没有则去数据库中拿,拿到后放进缓存,如果数据库中新增或者修改了数据,就需要同步一下缓存中的数据,其实只要将其删除就行了,例如:

//将内容数据插入到内容表        content.setCreated(new Date());        content.setUpdated(new Date());        //插入到数据库        contentMapper.insert(content);        //同步缓存        try {            Jedis jedis=JedisUtils.getJedis();            jedis.hdel(CONTENT_LIST, content.getCategoryId().toString());        } catch (Exception e) {            // TODO: handle exception        }        return E3Result.ok();

在插入数据库后将其对应的在缓存中的键值对删掉,这样在下一次查询时候就会到数据库中去拿值,然后重新写入缓存.

原创粉丝点击