Redis介绍及Mencached对比
Redis全称是远程字典服务,是一个Key-Value的存储系统,相比于很早之前一直使用的mencached,不单单提供了更多的类型支持。
数据类型上:mencached只支持简单的key-value存储,不支持持久化,不支持复制,不支持枚举,但是redis在数据结构上支持list、set、sorted set、hash,同时提供持久化与复制的功能。
内存机制上:mencached是进行全内存存储,就是所有的数据一直在内存中,但是redis并不是,它在进行内存存储的时候,根据swappability = age*log(size_in_memory)进行计算,计算出哪些值超过阈值,从而确定哪些值需要存储到磁盘,然后清除掉内存中的值。所以很多时候,Redis的存储是可以超过机器内存的值。
性能上:并不是说Redis性能一定比mencached更好,这里有个区间,在100k以上的数据中,mencached的性能高于Redis。
高可用上:mencached是全内存的缓存机制的,并不支持集群拓展,需要自己在客户端通过一致性哈希来实现,不过现在很少人这么做了,现在一般都是采用Redis Cluster来实现。
springboot2.2.X手册:是时候用Lettuce替换Jedis操作Redis缓存了
Jedis与Lettuce对比
这两个都是用于提供连接Redis的客户端。
Jedis是直接连接Redis,非线程安全,在性能上,每个线程都去拿自己的 Jedis 实例,当连接数量增多时,资源消耗阶梯式增大,连接成本就较高了。
Lettuce的连接是基于Netty的,Netty 是一个多线程、事件驱动的 I/O 框架。连接实例可以在多个线程间共享,当多线程使用同一连接实例时,是线程安全的。
springboot2.2.X手册:是时候用Lettuce替换Jedis操作Redis缓存了
引入包
1. <!-- redis核心包 -->
2. <dependency>
3. <groupId>org.springframework.boot</groupId>
4. <artifactId>spring-boot-starter-data-redis</artifactId>
5. </dependency>
6. <!-- 需要引入redis依赖包commons-pool -->
7. <dependency>
8. <groupId>org.apache.commons</groupId>
9. <artifactId>commons-pool2</artifactId>
10. </dependency>
编写配置类
1. /**
2. * All rights Reserved, Designed By 溪云阁
3. * Copyright: Copyright(C) 2016-2020
4. */
5. package com.module.boots.redis;
6. import org.springframework.boot.autoconfigure.AutoConfigureAfter;
7. import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
8. import org.springframework.context.annotation.Bean;
9. import org.springframework.context.annotation.Configuration;
10. import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
11. import org.springframework.data.redis.core.RedisTemplate;
12. import org.springframework.data.redis.serializer.StringRedisSerializer;
13. import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
14. /**
15. * Redis配置
16. * @author:溪云阁
17. * @date:2020年5月24日
18. */
19. @Configuration
20. @AutoConfigureAfter(RedisAutoConfiguration.class)
21. public class RedisConfig {
22. /**
23. * 采用FastJson进行key/value序列化
24. * @author 溪云阁
25. * @param redisConnectionFactory
26. * @return RedisTemplate<String,Object>
27. */
28. @Bean
29. public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {
30. final RedisTemplate<String, Object> template = new RedisTemplate<>();
31. // 使用fastjson序列化
32. final FastJsonRedisSerializer<?> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
33. // value值的序列化采用fastJsonRedisSerializer
34. template.setValueSerializer(fastJsonRedisSerializer);
35. template.setHashValueSerializer(fastJsonRedisSerializer);
36. // key的序列化采用StringRedisSerializer
37. template.setKeySerializer(new StringRedisSerializer());
38. template.setHashKeySerializer(new StringRedisSerializer());
39. // 开启事务
40. template.setEnableTransactionSupport(true);
41. template.setConnectionFactory(redisConnectionFactory);
42. return template;
43. }
44. }
编写工具类
1. package com.module.boots.redis;
2. import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.TimeUnit;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Component;import org.springframework.util.CollectionUtils;/**
3. * redis工具类
4. * @author:溪云阁
5. * @date:2020年5月24日
6. */
7. @Componentpublic class RedisUtils {
8. @Autowired
9. private RedisTemplate<String, Object> redisTemplate;
10. /** * 指定缓存失效时间 * @param key 键 * @param time 时间(秒) * @return */
11. public boolean expire(String key, long time) {
12. if (time > 0) {
13. redisTemplate.expire(key, time, TimeUnit.SECONDS);
14. return true;
15. } else {
16. throw new RuntimeException("超时时间小于0");
17. }
18. }
19. /**
20. * 根据key 获取过期时间 * @param key 键 不能为null * @return 时间(秒) 返回0代表为永久有效
21. */
22. public long getExpire(String key) {
23. return redisTemplate.getExpire(key, TimeUnit.SECONDS);
24. }
25. /**
26. * 判断key是否存在 * @param key 键 * @return true 存在 false不存在
27. */
28. public boolean hasKey(String key) {
29. return redisTemplate.hasKey(key);
30. }
31. /**
32. * 删除缓存 * @param key 可以传一个值 或多个 */
33. @SuppressWarnings("unchecked")
34. public void del(String... key) {
35. if (key != null && key.length > 0) {
36. if (key.length == 1) {
37. redisTemplate.delete(key[0]);
38. } else {
39. redisTemplate.delete(CollectionUtils.arrayToList(key));
40. }
41. }
42. }
43. // ============================String=============================
44. /**
45. * 普通缓存获取 * @param key 键 * @return 值 */
46. public Object get(String key) {
47. return key == null ? null : redisTemplate.opsForValue().get(key);
48. }
49. /**
50. * 普通缓存放入 * @param key 键 * @param value 值 * @return true成功 false失败
51. */
52. public boolean set(String key, Object value) {
53. redisTemplate.opsForValue().set(key, value);
54. return true;
55. }
56. /**
57. * 普通缓存放入并设置时间 * @param key 键 * @param value 值 * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
58. * @return true成功 false 失败
59. */
60. public boolean set(String key, Object value, long time) {
61. if (time > 0) {
62. redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
63. } else {
64. this.set(key, value);
65. }
66. return true;
67. }
68. /**
69. * 递增 * @param key 键 * @param by 要增加几(大于0)
70. * @return */
71. public long incr(String key, long delta) {
72. if (delta < 0) {
73. throw new RuntimeException("递增因子必须大于0");
74. }
75. return redisTemplate.opsForValue().increment(key, delta);
76. }
77. /**
78. * 递减 * @param key 键 * @param by 要减少几(小于0)
79. * @return */
80. public long decr(String key, long delta) {
81. if (delta < 0) {
82. throw new RuntimeException("递减因子必须大于0");
83. }
84. return redisTemplate.opsForValue().increment(key, -delta);
85. }
86. // ================================Map=================================
87. /**
88. * HashGet * @param key 键 不能为null * @param item 项 不能为null * @return 值 */
89. public Object hget(String key, String item) {
90. return redisTemplate.opsForHash().get(key, item);
91. }
92. /**
93. * 获取hashKey对应的所有键值 * @param key 键 * @return 对应的多个键值 */
94. public Map<Object, Object> hmget(String key) {
95. return redisTemplate.opsForHash().entries(key);
96. }
97. /**
98. * HashSet * @param key 键 * @param map 对应多个键值 * @return true 成功 false 失败
99. */
100. public boolean hmset(String key, Map<String, Object> map) {
101. redisTemplate.opsForHash().putAll(key, map);
102. return true;
103. }
104. /**
105. * HashSet 并设置时间 * @param key 键 * @param map 对应多个键值 * @param time 时间(秒) * @return true成功 false失败
106. */
107. public boolean hmset(String key, Map<String, Object> map, long time) {
108. redisTemplate.opsForHash().putAll(key, map);
109. if (time > 0) {
110. expire(key, time);
111. }
112. return true;
113. }
114. /**
115. * 向一张hash表中放入数据,如果不存在将创建 * @param key 键 * @param item 项 * @param value 值 * @return true 成功 false失败
116. */
117. public boolean hset(String key, String item, Object value) {
118. redisTemplate.opsForHash().put(key, item, value);
119. return true;
120. }
121. /**
122. * 向一张hash表中放入数据,如果不存在将创建 * @param key 键 * @param item 项 * @param value 值 * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
123. * @return true 成功 false失败
124. */
125. public boolean hset(String key, String item, Object value, long time) {
126. redisTemplate.opsForHash().put(key, item, value);
127. if (time > 0) {
128. expire(key, time);
129. }
130. return true;
131. }
132. /**
133. * 删除hash表中的值 * @param key 键 不能为null * @param item 项 可以使多个 不能为null */
134. public void hdel(String key, Object... item) {
135. redisTemplate.opsForHash().delete(key, item);
136. }
137. /**
138. * 判断hash表中是否有该项的值 * @param key 键 不能为null * @param item 项 不能为null * @return true 存在 false不存在
139. */
140. public boolean hHasKey(String key, String item) {
141. return redisTemplate.opsForHash().hasKey(key, item);
142. }
143. /**
144. * hash递增 如果不存在,就会创建一个 并把新增后的值返回 * @param key 键 * @param item 项 * @param by 要增加几(大于0)
145. * @return */
146. public double hincr(String key, String item, double by) {
147. return redisTemplate.opsForHash().increment(key, item, by);
148. }
149. /**
150. * hash递减 * @param key 键 * @param item 项 * @param by 要减少记(小于0)
151. * @return */
152. public double hdecr(String key, String item, double by) {
153. return redisTemplate.opsForHash().increment(key, item, -by);
154. }
155. // ============================set=============================
156. /**
157. * 根据key获取Set中的所有值 * @param key 键 * @return */
158. public Set<Object> sGet(String key) {
159. return redisTemplate.opsForSet().members(key);
160. }
161. /**
162. * 根据value从一个set中查询,是否存在 * @param key 键 * @param value 值 * @return true 存在 false不存在
163. */
164. public boolean sHasKey(String key, Object value) {
165. return redisTemplate.opsForSet().isMember(key, value);
166. }
167. /**
168. * 将数据放入set缓存 * @param key 键 * @param values 值 可以是多个 * @return 成功个数 */
169. public long sSet(String key, Object... values) {
170. return redisTemplate.opsForSet().add(key, values);
171. }
172. /**
173. * 将set数据放入缓存 * @param key 键 * @param time 时间(秒) * @param values 值 可以是多个 * @return 成功个数 */
174. public long sSetAndTime(String key, long time, Object... values) {
175. final Long count = redisTemplate.opsForSet().add(key, values);
176. if (time > 0)
177. expire(key, time);
178. return count;
179. }
180. /**
181. * 获取set缓存的长度 * @param key 键 * @return */
182. public long sGetSetSize(String key) {
183. return redisTemplate.opsForSet().size(key);
184. }
185. /**
186. * 移除值为value的 * @param key 键 * @param values 值 可以是多个 * @return 移除的个数 */
187. public long setRemove(String key, Object... values) {
188. final Long count = redisTemplate.opsForSet().remove(key, values);
189. return count;
190. }
191. // ===============================list=================================
192. /**
193. * 获取list缓存的内容 * @param key 键 * @param start 开始 * @param end 结束 0 到 -1代表所有值
194. * @return */
195. public List<Object> lGet(String key, long start, long end) {
196. return redisTemplate.opsForList().range(key, start, end);
197. }
198. /**
199. * 获取list缓存的长度 * @param key 键 * @return */
200. public long lGetListSize(String key) {
201. return redisTemplate.opsForList().size(key);
202. }
203. /**
204. * 通过索引 获取list中的值 * @param key 键 * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
205. * @return */
206. public Object lGetIndex(String key, long index) {
207. return redisTemplate.opsForList().index(key, index);
208. }
209. /**
210. * 将list放入缓存 * @param key 键 * @param value 值 * @param time 时间(秒) * @return */
211. public boolean lSet(String key, Object value) {
212. redisTemplate.opsForList().rightPush(key, value);
213. return true;
214. }
215. /**
216. * 将list放入缓存 * @param key 键 * @param value 值 * @param time 时间(秒) * @return */
217. public boolean lSet(String key, Object value, long time) {
218. redisTemplate.opsForList().rightPush(key, value);
219. if (time > 0) {
220. expire(key, time);
221. }
222. return true;
223. }
224. /**
225. * 将list放入缓存 * @param key 键 * @param value 值 * @param time 时间(秒) * @return */
226. public boolean lSet(String key, List<Object> value) {
227. redisTemplate.opsForList().rightPushAll(key, value);
228. return true;
229. }
230. /**
231. * 将list放入缓存 * @param key 键 * @param value 值 * @param time 时间(秒) * @return */
232. public boolean lSet(String key, List<Object> value, long time) {
233. redisTemplate.opsForList().rightPushAll(key, value);
234. if (time > 0) {
235. expire(key, time);
236. }
237. return true;
238. }
239. /**
240. * 根据索引修改list中的某条数据 * @param key 键 * @param index 索引 * @param value 值 * @return */
241. public boolean lUpdateIndex(String key, long index, Object value) {
242. redisTemplate.opsForList().set(key, index, value);
243. return true;
244. }
245. }
编写配置文件
1. #redis地址
2. spring.redis.host: 127.0.0.1
3. #redis端口号
4. spring.redis.port: 6379
5. #redis密码,如果没有不用填写,建议还是得有
6. spring.redis.password: 123456
7. #最大活跃连接数,默认是8spring.redis.lettuce.pool.maxActive: 100
8. #最大空闲连接数 ,默认是8spring.redis.lettuce.pool.maxIdle: 100
9. #最小空闲连接数 ,默认是0spring.redis.lettuce.pool.minIdle: 0
编写测试类
1. /**
2. * All rights Reserved, Designed By 溪云阁
3. * Copyright: Copyright(C) 2016-2020
4. */
5. package com.boots.redis;
6. import org.junit.Before;
7. import org.junit.Test;
8. import org.junit.runner.RunWith;
9. import org.springframework.beans.factory.annotation.Autowired;
10. import org.springframework.boot.test.context.SpringBootTest;
11. import org.springframework.test.context.junit4.SpringRunner;
12. import com.module.boots.redis.RedisUtils;
13. /**
14. * redis单元测试
15. * @author:溪云阁
16. * @date:2020年5月24日
17. */
18. @RunWith(SpringRunner.class)
19. @SpringBootTest
20. public class BootsRedisApplicationTest {
21. @Autowired
22. private RedisUtils redisUtils; /**
23. * 执行前插入值
24. * @author 溪云阁
25. * @throws Exception void
26. */
27. @Before
28. public void setUp() throws Exception { redisUtils.set("aaa", "121212");
29. System.out.println("插入值成功");
30. } /**
31. * 执行获取值
32. * @author 溪云阁
33. * @throws Exception void
34. */
35. @Test
36. public void test() throws Exception { System.out.println(redisUtils.get("aaa"));
37. }}