您的位置:首页 > 数据库 > Redis

redis实现 spring-redis-data初学习

2013-07-25 19:28 453 查看
今天看了一些redis的客户端实现、主要分为spring-redis-data 、jredis

今天先记录下spring-redis-data的学习心得;

spring-redis-data 中我目前主要用了它的存、取、清除。

先看配置吧redis-manager-config.properties :

[html] view
plaincopy

redis.host=192.168.1.20//redis的服务器地址  

redis.port=6400//redis的服务端口  

redis.pass=1234xxxxx//密码  

redis.default.db=0//链接数据库  

redis.timeout=100000//客户端超时时间单位是毫秒  

redis.maxActive=300// 最大连接数  

redis.maxIdle=100//最大空闲数  

[html] view
plaincopy

redis.maxWait=1000//最大建立连接等待时间  

redis.testOnBorrow=true//<span style="font-size:12px;">指明是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个</span>  

spring 中配置

[html] view
plaincopy

<bean id="propertyConfigurerRedis" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  

        <property name="order" value="1" />  

        <property name="ignoreUnresolvablePlaceholders" value="true" />  

        <property name="locations">  

            <list>  

                <value>classpath:config/redis-manager-config.properties</value>  

            </list>  

        </property>  

    </bean>  

      

        <!-- jedis pool配置 -->  

    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  

        <property name="maxActive" value="${redis.maxActive}" />  

        <property name="maxIdle" value="${redis.maxIdle}" />  

        <property name="maxWait" value="${redis.maxWait}" />  

        <property name="testOnBorrow" value="${redis.testOnBorrow}" />  

    </bean>  

  

    <!-- spring data redis -->  

    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">  

        <property name="usePool" value="true"></property>  

        <property name="hostName" value="${redis.host}" />  

        <property name="port" value="${redis.port}" />  

        <property name="password" value="${redis.pass}" />  

        <property name="timeout" value="${redis.timeout}" />  

        <property name="database" value="${redis.default.db}"></property>  

        <constructor-arg index="0" ref="jedisPoolConfig" />  

    </bean>  

      

    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  

        <property name="connectionFactory" ref="jedisConnectionFactory" />  

    </bean>  

[html] view
plaincopy

   

[html] view
plaincopy

<!--配置一个基础类(之后的业务类继承于该类)、将redisTemplate注入 -->  

[html] view
plaincopy

<bean id="redisBase" abstract="true">  

  <property name="template" ref="redisTemplate"></property>  

 </bean>  

java代码:

[java] view
plaincopy

public class RedisBase {  

  

    private StringRedisTemplate template;  

  

    /** 

     * @return the template 

     */  

    public StringRedisTemplate getTemplate() {  

        return template;  

    }  

  

    /** 

     * @param template the template to set 

     */  

    public void setTemplate(StringRedisTemplate template) {  

        this.template = template;  

    }  

  

}  

继续:

下面就是具体redis的值的写入、读出、清除缓存喽!

第一:写入

[java] view
plaincopy

public class StudentCountDO {  

  

    private Long id;  

  

       private String studentId;  

  

        private Long commentHeadCount;  

  

       private Long docAttitudeScores;  

  

       private Long guideServiceScores;  

  

        private Long treatEffectCount;  

  

       private Long treatEffectScores;  

  

    private String gmtModified;  

  

    private String gmtCreated;  

  

        private Long waitingTimeScores;  

  

   }  

 

[java] view
plaincopy

StringRedisTemplate template = getTemplate();//获得上面注入的template  

       // save as hash 一般key都要加一个前缀,方便清除所有的这类key  

       BoundHashOperations<String, String, String> ops = template.boundHashOps("student:"+studentCount.getStudentId());  

  

       Map<String, String> data = new HashMap<String, String>();  

       data.put("studentId", CommentUtils.convertNull(studentCount.getStudentId()));  

       data.put("commentHeadCount", CommentUtils.convertLongToString(studentCount.getCommentHeadCount()));  

       data.put("docAttitudeScores", CommentUtils.convertLongToString(studentCount.getDocAttitudeScores()));  

       data.put("guideServicesScores", CommentUtils.convertLongToString(studentCount.getGuideServiceScores()));  

       data.put("treatEffectCount", CommentUtils.convertLongToString(studentCount.getTreatEffectCount()));  

       data.put("treatEffectScores", CommentUtils.convertLongToString(studentCount.getTreatEffectScores()));  

       data.put("waitingTimeScores", CommentUtils.convertLongToString(studentCount.getWaitingTimeScores()));  

       try {  

           ops.putAll(data);  

       } catch (Exception e) {  

           logger.error(CommentConstants.WRITE_EXPERT_COMMENT_COUNT_REDIS_ERROR + studentCount.studentCount(), e);  

       }  

第二、 取出

[java] view
plaincopy

public StudentCountDO getStudentCommentCountInfo(String studentId) {  

       final String strkey = "student:"+ studentId;  

       return getTemplate().execute(new RedisCallback<StudentCountDO>() {  

           @Override  

           public StudentCountDO doInRedis(RedisConnection connection) throws DataAccessException {  

               byte[] bkey = getTemplate().getStringSerializer().serialize(strkey);  

               if (connection.exists(bkey)) {  

                   List<byte[]> value = connection.hMGet(bkey,  

                           getTemplate().getStringSerializer().serialize("studentId"), getTemplate()  

                                   .getStringSerializer().serialize("commentHeadCount"), getTemplate()  

                                   .getStringSerializer().serialize("docAttitudeScores"), getTemplate()  

                                   .getStringSerializer().serialize("guideServicesScores"), getTemplate()  

                                   .getStringSerializer().serialize("treatEffectCount"), getTemplate()  

                                   .getStringSerializer().serialize("treatEffectScores"), getTemplate()  

                                   .getStringSerializer().serialize("waitingTimeScores"));  

                   StudentCountDO studentCommentCountDO = new StudentCountDO();  

                   studentCommentCountDO.setExpertId(getTemplate().getStringSerializer().deserialize(value.get(0)));  

                   studentCommentCountDO.setCommentHeadCount(Long.parseLong(getTemplate().getStringSerializer()  

                           .deserialize(value.get(1))));  

                   studentCommentCountDO.setDocAttitudeScores(Long.parseLong(getTemplate().getStringSerializer()  

                           .deserialize(value.get(2))));  

                   studentCommentCountDO.setGuideServiceScores(Long.parseLong(getTemplate().getStringSerializer()  

                           .deserialize(value.get(3))));  

                   studentCommentCountDO.setTreatEffectCount(Long.parseLong(getTemplate().getStringSerializer()  

                           .deserialize(value.get(4))));  

                   studentCommentCountDO.setTreatEffectScores(Long.parseLong(getTemplate().getStringSerializer()  

                           .deserialize(value.get(5))));  

                   studentCommentCountDO.setWaitingTimeScores(Long.parseLong(getTemplate().getStringSerializer()  

                           .deserialize(value.get(6))));  

                   return studentCommentCountDO;  

               }  

               return null;  

           }  

       });  

   }  

这个存和取的过程其实是把对象中的各个字段序列化之后存入到hashmap 、取出来的时候在进行按照存入进去的顺序进行取出。

第三 清除

这个就根据前面的前缀很简单了,一句代码就搞定啦!

[java] view
plaincopy

private void clear(String pattern) {  

       StringRedisTemplate template = getTemplate();  

       Set<String> keys = template.keys(pattern);  

       if (!keys.isEmpty()) {  

           template.delete(keys);  

       }  

   }  

pattern传入为student: 就可以将该类型的所有缓存清除掉喽!

1, Redis Hello World 的例子  
  
这里用的包是Jedis。下载地址https://github.com/xetorthio/jedis/downloads  
  
把jar包引入工程,打开redis的服务器(redis下载及安装见初步理解Redis及其安装配置)。开始打招呼的例子,如下  
  
   1:  Jedis jedis = new Jedis("localhost");  
  
   2:  jedis.set("key", "Hello World!");  
  
   3:  String value = jedis.get("key");  
  
   4:  System.out.println(value);  
  
分别测试下各种数据结构  
  
        System.out.println("==String==");  
  
        Jedis jedis = new Jedis("localhost");  
  
        //String   
  
        jedis.set("key", "Hello World!");  
  
        String value = jedis.get("key");  
  
        System.out.println(value);  
  
          
  
        //List   
  
        System.out.println("==List==");  
  
        jedis.rpush("messages", "Hello how are you?");  
  
        jedis.rpush("messages", "Fine thanks. I'm having fun with redis.");  
  
        jedis.rpush("messages", "I should look into this NOSQL thing ASAP");  
  
        List<String> values = jedis.lrange("messages", 0, -1);  
  
        System.out.println(values);  
  
          
  
        //Set   
  
        System.out.println("==Set==");  
  
        jedis.sadd("myset", "1");  
  
        jedis.sadd("myset", "2");  
  
        jedis.sadd("myset", "3");  
  
        jedis.sadd("myset", "4");  
  
        Set<String> setValues = jedis.smembers("myset");  
  
        System.out.println(setValues);  
  
          
  
        //Sorted Set   
  
        jedis.zadd("hackers", 1940, "Alan Kay");  
  
        jedis.zadd("hackers", 1953, "Richard Stallman");  
  
        jedis.zadd("hackers", 1965, "Yukihiro Matsumoto");  
  
        jedis.zadd("hackers", 1916, "Claude Shannon");  
  
        jedis.zadd("hackers", 1969, "Linus Torvalds");  
  
        jedis.zadd("hackers", 1912, "Alan Turing");  
  
        setValues = jedis.zrange("hackers", 0, -1);  
  
        System.out.println(setValues);  
  
          
  
        //Hash   
  
        System.out.println("==Hash==");  
  
        Map<String, String> pairs = new HashMap<String, String>();  
  
        pairs.put("name", "Akshi");  
  
        pairs.put("age", "2");  
  
        pairs.put("sex", "Female");  
  
        jedis.hmset("kid", pairs);  
  
        values = jedis.hmget("kid", new String[]{"name", "age", "sex"});  
  
        System.out.println(values);  
  
          
  
        setValues = jedis.hkeys("kid");  
  
        System.out.println(setValues);  
  
        values = jedis.hvals("kid");  
  
        System.out.println(values);  
  
        pairs = jedis.hgetAll("kid");  
  
        System.out.println(pairs);  
  
然后解决持久化的问题  
  
redis是把所有的数据都放在内存的一种机制,需要经常同步到磁盘保证数据的持久化。数据全放在内存里,真的很担心我的小机器啊~回头数据大了调台式机上把,再大了就。。。  
  
这个题目比较大些,以后可以单独写几篇,现在急着用,入门么,解决问题先。主要是两种机制,快照(Snapshotting)和AOF(Append-only file)。AOF每次写操作都会写日志,服务器当机的时候从那些日志文件里恢复。不过日志文件会特别大,我的机器肯定承受不起。快照是默认的方式,默认是每小时更新一次,手动调用save, shutdown, slave这些命令也会写日志。测试下save。  
  
先用客户端查询一下刚才代码插入的东西。  
  
image  
  
东西还是在内存里的。然后把服务器关了。重新开启,还是有结果。  
  
image  
  
验证是不是因为时间过太久了自动保存了,用java代码新插入一个值。继续关服务器和重启等操作。  
  
image  
  
没有值。证明之前的值存在确实是因为自动保存了,接着重新插入(这个如果覆盖是个什么情况呢:貌似直接无情地覆盖了),然后执行下保存。之后关闭,重启。  
  
jedis.set("newkey", "Hello New New World!");  
String value = jedis.get("newkey");  
System.out.println(value);  
jedis.save();  
  
image  
  
可以看到newkey的值了,而且是覆盖后的。save执行后会进行一次日志备份。够用了,先到这里吧。  
转载于http://blog.csdn.net/samtribiani/article/details/7609322
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: