今天看了一些redis的客户端实现、主要分为spring-redis-data 、jredis

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

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

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


[html]  view plain copy


1. redis.host=192.168.1.20//redis的服务器地址  
2. redis.port=6400//redis的服务端口  
3. redis.pass=1234xxxxx//密码  
4. redis.default.db=0//链接数据库  
5. redis.timeout=100000//客户端超时时间单位是毫秒  
6. redis.maxActive=300// 最大连接数  
7. redis.maxIdle=100//最大空闲数


[html]  view plain copy



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


spring 中配置


[html]  view plain copy


1. <bean id="propertyConfigurerRedis" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
2. <property name="order" value="1" />  
3. <property name="ignoreUnresolvablePlaceholders" value="true" />  
4. <property name="locations">  
5. <list>  
6. <value>classpath:config/redis-manager-config.properties</value>  
7. </list>  
8. </property>  
9. </bean>  
10.       
11. <!-- jedis pool配置 -->  
12. <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  
13. <property name="maxActive" value="${redis.maxActive}" />  
14. <property name="maxIdle" value="${redis.maxIdle}" />  
15. <property name="maxWait" value="${redis.maxWait}" />  
16. <property name="testOnBorrow" value="${redis.testOnBorrow}" />  
17. </bean>  
18.   
19. <!-- spring data redis -->  
20. <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">  
21. <property name="usePool" value="true"></property>  
22. <property name="hostName" value="${redis.host}" />  
23. <property name="port" value="${redis.port}" />  
24. <property name="password" value="${redis.pass}" />  
25. <property name="timeout" value="${redis.timeout}" />  
26. <property name="database" value="${redis.default.db}"></property>  
27. <constructor-arg index="0" ref="jedisPoolConfig" />  
28. </bean>  
29.       
30. <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
31. <property name="connectionFactory" ref="jedisConnectionFactory" />  
32. </bean>

[html]  view plain copy



[html]  view plain copy



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


[html]  view plain copy


1. <bean id="redisBase" abstract="true">  
2. <property name="template" ref="redisTemplate"></property>  
3. </bean>



java代码:


[java]  view plain copy


1. public class RedisBase {  
2.   
3. private StringRedisTemplate template;  
4.   
5. /**
6.      * @return the template
7.      */  
8. public StringRedisTemplate getTemplate() {  
9. return template;  
10.     }  
11.   
12. /**
13.      * @param template the template to set
14.      */  
15. public void setTemplate(StringRedisTemplate template) {  
16. this.template = template;  
17.     }  
18.   
19. }

继续:

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

第一:写入


[java]  view plain copy



    1. public class StudentCountDO {  
    2.   
    3. private Long id;  
    4.   
    5. private String studentId;  
    6.   
    7. private Long commentHeadCount;  
    8.   
    9. private Long docAttitudeScores;  
    10.   
    11. private Long guideServiceScores;  
    12.   
    13. private Long treatEffectCount;  
    14.   
    15. private Long treatEffectScores;  
    16.   
    17. private String gmtModified;  
    18.   
    19. private String gmtCreated;  
    20.   
    21. private Long waitingTimeScores;  
    22.   
    23.    }



     


    [java]  view plain copy

    1. StringRedisTemplate template = getTemplate();//获得上面注入的template  
    2. // save as hash 一般key都要加一个前缀,方便清除所有的这类key  
    3. "student:"+studentCount.getStudentId());  
    4.   
    5. new HashMap<String, String>();  
    6. "studentId", CommentUtils.convertNull(studentCount.getStudentId()));  
    7. "commentHeadCount", CommentUtils.convertLongToString(studentCount.getCommentHeadCount()));  
    8. "docAttitudeScores", CommentUtils.convertLongToString(studentCount.getDocAttitudeScores()));  
    9. "guideServicesScores", CommentUtils.convertLongToString(studentCount.getGuideServiceScores()));  
    10. "treatEffectCount", CommentUtils.convertLongToString(studentCount.getTreatEffectCount()));  
    11. "treatEffectScores", CommentUtils.convertLongToString(studentCount.getTreatEffectScores()));  
    12. "waitingTimeScores", CommentUtils.convertLongToString(studentCount.getWaitingTimeScores()));  
    13. try {  
    14.            ops.putAll(data);  
    15. catch (Exception e) {  
    16.            logger.error(CommentConstants.WRITE_EXPERT_COMMENT_COUNT_REDIS_ERROR + studentCount.studentCount(), e);  
    17.        }


    第二、 取出


    [java]  view plain copy



    1. public StudentCountDO getStudentCommentCountInfo(String studentId) {  
    2. final String strkey = "student:"+ studentId;  
    3. return getTemplate().execute(new RedisCallback<StudentCountDO>() {  
    4. @Override  
    5. public StudentCountDO doInRedis(RedisConnection connection) throws DataAccessException {  
    6. byte[] bkey = getTemplate().getStringSerializer().serialize(strkey);  
    7. if (connection.exists(bkey)) {  
    8. byte[]> value = connection.hMGet(bkey,  
    9. "studentId"), getTemplate()  
    10. "commentHeadCount"), getTemplate()  
    11. "docAttitudeScores"), getTemplate()  
    12. "guideServicesScores"), getTemplate()  
    13. "treatEffectCount"), getTemplate()  
    14. "treatEffectScores"), getTemplate()  
    15. "waitingTimeScores"));  
    16. new StudentCountDO();  
    17. 0)));  
    18.                    studentCommentCountDO.setCommentHeadCount(Long.parseLong(getTemplate().getStringSerializer()  
    19. 1))));  
    20.                    studentCommentCountDO.setDocAttitudeScores(Long.parseLong(getTemplate().getStringSerializer()  
    21. 2))));  
    22.                    studentCommentCountDO.setGuideServiceScores(Long.parseLong(getTemplate().getStringSerializer()  
    23. 3))));  
    24.                    studentCommentCountDO.setTreatEffectCount(Long.parseLong(getTemplate().getStringSerializer()  
    25. 4))));  
    26.                    studentCommentCountDO.setTreatEffectScores(Long.parseLong(getTemplate().getStringSerializer()  
    27. 5))));  
    28.                    studentCommentCountDO.setWaitingTimeScores(Long.parseLong(getTemplate().getStringSerializer()  
    29. 6))));  
    30. return studentCommentCountDO;  
    31.                }  
    32. return null;  
    33.            }  
    34.        });  
    35.    }


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

    第三 清除

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


    [java]  view plain copy


    1. private void clear(String pattern) {  
    2.        StringRedisTemplate template = getTemplate();  
    3.        Set<String> keys = template.keys(pattern);  
    4. if (!keys.isEmpty()) {  
    5.            template.delete(keys);  
    6.        }  
    7.    }


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

    1. 1, Redis Hello World 的例子  
    2.   
    3. 这里用的包是Jedis。下载地址https://github.com/xetorthio/jedis/downloads
    4.   
    5. 把jar包引入工程,打开redis的服务器(redis下载及安装见初步理解Redis及其安装配置)。开始打招呼的例子,如下  
    6.   
    7. 1:  Jedis jedis = new Jedis("localhost");  
    8.   
    9. 2:  jedis.set("key", "Hello World!");  
    10.   
    11. 3:  String value = jedis.get("key");  
    12.   
    13. 4:  System.out.println(value);  
    14.   
    15. 分别测试下各种数据结构  
    16.   
    17. "==String==");  
    18.   
    19. new Jedis("localhost");  
    20.   
    21. //String 
    22.   
    23. "key", "Hello World!");  
    24.   
    25. "key");  
    26.   
    27.         System.out.println(value);  
    28.   
    29.           
    30.   
    31. //List 
    32.   
    33. "==List==");  
    34.   
    35. "messages", "Hello how are you?");  
    36.   
    37. "messages", "Fine thanks. I'm having fun with redis.");  
    38.   
    39. "messages", "I should look into this NOSQL thing ASAP");  
    40.   
    41. "messages", 0, -1);  
    42.   
    43.         System.out.println(values);  
    44.   
    45.           
    46.   
    47. //Set 
    48.   
    49. "==Set==");  
    50.   
    51. "myset", "1");  
    52.   
    53. "myset", "2");  
    54.   
    55. "myset", "3");  
    56.   
    57. "myset", "4");  
    58.   
    59. "myset");  
    60.   
    61.         System.out.println(setValues);  
    62.   
    63.           
    64.   
    65. //Sorted Set 
    66.   
    67. "hackers", 1940, "Alan Kay");  
    68.   
    69. "hackers", 1953, "Richard Stallman");  
    70.   
    71. "hackers", 1965, "Yukihiro Matsumoto");  
    72.   
    73. "hackers", 1916, "Claude Shannon");  
    74.   
    75. "hackers", 1969, "Linus Torvalds");  
    76.   
    77. "hackers", 1912, "Alan Turing");  
    78.   
    79. "hackers", 0, -1);  
    80.   
    81.         System.out.println(setValues);  
    82.   
    83.           
    84.   
    85. //Hash 
    86.   
    87. "==Hash==");  
    88.   
    89. new
    90.   
    91. "name", "Akshi");  
    92.   
    93. "age", "2");  
    94.   
    95. "sex", "Female");  
    96.   
    97. "kid", pairs);  
    98.   
    99. "kid", new String[]{"name", "age", "sex"});  
    100.   
    101.         System.out.println(values);  
    102.   
    103.           
    104.   
    105. "kid");  
    106.   
    107.         System.out.println(setValues);  
    108.   
    109. "kid");  
    110.   
    111.         System.out.println(values);  
    112.   
    113. "kid");  
    114.   
    115.         System.out.println(pairs);
    1.   
    2. 然后解决持久化的问题  
    3.   
    4. redis是把所有的数据都放在内存的一种机制,需要经常同步到磁盘保证数据的持久化。数据全放在内存里,真的很担心我的小机器啊~回头数据大了调台式机上把,再大了就。。。  
    5.   
    6. 这个题目比较大些,以后可以单独写几篇,现在急着用,入门么,解决问题先。主要是两种机制,快照(Snapshotting)和AOF(Append-only file)。AOF每次写操作都会写日志,服务器当机的时候从那些日志文件里恢复。不过日志文件会特别大,我的机器肯定承受不起。快照是默认的方式,默认是每小时更新一次,手动调用save, shutdown, slave这些命令也会写日志。测试下save。  
    7.   
    8. 先用客户端查询一下刚才代码插入的东西。  
    9.   
    10. image  
    11.   
    12. 东西还是在内存里的。然后把服务器关了。重新开启,还是有结果。  
    13.   
    14. image  
    15.   
    16. 验证是不是因为时间过太久了自动保存了,用java代码新插入一个值。继续关服务器和重启等操作。  
    17.   
    18. image  
    19.   
    20. 没有值。证明之前的值存在确实是因为自动保存了,接着重新插入(这个如果覆盖是个什么情况呢:貌似直接无情地覆盖了),然后执行下保存。之后关闭,重启。  
    1.   
    2. jedis.set("newkey", "Hello New New World!");  
    3. String value = jedis.get("newkey");  
    4. System.out.println(value);  
    5. jedis.save();  
    6.   
    7. image
    1.   
    2. 可以看到newkey的值了,而且是覆盖后的。save执行后会进行一次日志备份。够用了,先到这里吧。