SpringBoot整合Redis-单机版

╰+哭是因爲堅強的太久メ 2024-03-24 12:17 145阅读 0赞

1、创建一个springboot工程

2、在pom.xml中导入Redis的相关依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>
  5. <!-- spring2.X集成redis所需common-pool2-->
  6. <dependency>
  7. <groupId>org.apache.commons</groupId>
  8. <artifactId>commons-pool2</artifactId>
  9. <version>2.6.0</version>
  10. </dependency>

3、在application.properties中配置redis

  1. #springboot2.x之后,默认使用的client是lettuce,而不是jedis了
  2. # Redis数据库索引(默认为0)
  3. spring.redis.database=0
  4. # Redis服务器地址
  5. spring.redis.host=127.0.0.1
  6. # Redis服务器连接端口
  7. spring.redis.port=6379
  8. # Redis服务器连接密码(默认为空)
  9. #spring.redis.password=123456
  10. #连接超时时间(毫秒)
  11. spring.redis.timeout=1800000
  12. #连接池最大连接数(使用负值表示没有限制)
  13. spring.redis.lettuce.pool.max-active=20
  14. #最大阻塞等待时间(负数表示没限制)
  15. spring.redis.lettuce.pool.max-wait=-1
  16. #连接池中的最大空闲连接
  17. spring.redis.lettuce.pool.max-idle=5
  18. #连接池中的最小空闲连接
  19. spring.redis.lettuce.pool.min-idle=0

4、添加Redis的配置类

  1. package com.andrew.config;
  2. import org.springframework.cache.annotation.CachingConfigurerSupport;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.data.redis.connection.RedisConnectionFactory;
  6. import org.springframework.data.redis.core.RedisTemplate;
  7. import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
  8. import org.springframework.data.redis.serializer.StringRedisSerializer;
  9. @Configuration
  10. public class RedisConfig extends CachingConfigurerSupport {
  11. @Bean
  12. public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
  13. RedisTemplate<String, Object> template = new RedisTemplate<>();
  14. template.setConnectionFactory(factory);
  15. // key采用String的序列化方式
  16. template.setKeySerializer(new StringRedisSerializer());
  17. // hash的key也采用String的序列化方式
  18. template.setHashKeySerializer(new StringRedisSerializer());
  19. // value序列化方式采用jackson
  20. template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
  21. // hash的value序列化方式采用jackson
  22. template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
  23. template.afterPropertiesSet();
  24. return template;
  25. }
  26. }

5、测试

  1. @RestController
  2. @RequestMapping("/redis")
  3. public class RedisTestController {
  4. @Autowired
  5. private RedisTemplate redisTemplate;
  6. @Autowired
  7. private RedisUtil redisUtil;
  8. @GetMapping("test1")
  9. public String test1() {
  10. redisTemplate.opsForValue().set("name","lucy");
  11. String name = (String)redisTemplate.opsForValue().get("name");
  12. return name;
  13. }
  14. @GetMapping("test2")
  15. public String test2() {
  16. redisUtil.set("age", "12");
  17. String age = (String) redisUtil.get("age");
  18. return age;
  19. }
  20. }

贴个RedisUtil:

  1. @Component
  2. public class RedisUtil {
  3. @Resource
  4. private RedisTemplate redisTemplate;
  5. private static double size = Math.pow(2, 32);
  6. /**
  7. * 写入缓存
  8. *
  9. * @param key
  10. * @param offset 位 8Bit=1Byte
  11. * @return
  12. */
  13. public boolean setBit(String key, long offset, boolean isShow) {
  14. boolean result = false;
  15. try {
  16. ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
  17. operations.setBit(key, offset, isShow);
  18. result = true;
  19. } catch (Exception e) {
  20. e.printStackTrace();
  21. }
  22. return result;
  23. }
  24. /**
  25. * 得到缓存
  26. *
  27. * @param key
  28. * @param offset
  29. * @return
  30. */
  31. public boolean getBit(String key, long offset) {
  32. boolean result = false;
  33. try {
  34. ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
  35. result = operations.getBit(key, offset);
  36. } catch (Exception e) {
  37. e.printStackTrace();
  38. }
  39. return result;
  40. }
  41. /**
  42. * 写入缓存
  43. * @param key
  44. * @param value
  45. * @return
  46. */
  47. public boolean set(final String key, Object value) {
  48. boolean result = false;
  49. try {
  50. ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
  51. operations.set(key, value);
  52. result = true;
  53. } catch (Exception e) {
  54. e.printStackTrace();
  55. }
  56. return result;
  57. }
  58. /**
  59. * 写入缓存设置时效时间
  60. * @param key
  61. * @param value
  62. * @return
  63. */
  64. public boolean set(final String key, Object value, Long expireTime) {
  65. boolean result = false;
  66. try {
  67. ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
  68. operations.set(key, value);
  69. redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
  70. result = true;
  71. } catch (Exception e) {
  72. e.printStackTrace();
  73. }
  74. return result;
  75. }
  76. /**
  77. * 批量删除对应的value
  78. *
  79. * @param keys
  80. */
  81. public void remove(final String... keys) {
  82. for (String key : keys) {
  83. remove(key);
  84. }
  85. }
  86. /**
  87. * 删除对应的value
  88. *
  89. * @param key
  90. */
  91. public void remove(final String key) {
  92. if (exists(key)) {
  93. redisTemplate.delete(key);
  94. }
  95. }
  96. /**
  97. * 判断缓存中是否有对应的value
  98. *
  99. * @param key
  100. * @return
  101. */
  102. public boolean exists(final String key) {
  103. return redisTemplate.hasKey(key);
  104. }
  105. /**
  106. * 读取缓存
  107. *
  108. * @param key
  109. * @return
  110. */
  111. public Object get(final String key) {
  112. Object result = null;
  113. ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
  114. result = operations.get(key);
  115. return result;
  116. }
  117. /**
  118. * 哈希 添加
  119. *
  120. * @param key
  121. * @param hashKey
  122. * @param value
  123. */
  124. public void hmSet(String key, Object hashKey, Object value) {
  125. HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
  126. hash.put(key, hashKey, value);
  127. }
  128. /**
  129. * 哈希获取数据
  130. *
  131. * @param key
  132. * @param hashKey
  133. * @return
  134. */
  135. public Object hmGet(String key, Object hashKey) {
  136. HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
  137. return hash.get(key, hashKey);
  138. }
  139. /**
  140. * 列表添加
  141. *
  142. * @param k
  143. * @param v
  144. */
  145. public void lPush(String k, Object v) {
  146. ListOperations<String, Object> list = redisTemplate.opsForList();
  147. list.leftPush(k, v);
  148. }
  149. /**
  150. * 列表添加
  151. *
  152. * @param k
  153. * @param v
  154. */
  155. public void rPush(String k, Object v) {
  156. ListOperations<String, Object> list = redisTemplate.opsForList();
  157. list.rightPush(k, v);
  158. }
  159. /**
  160. * 左弹出数列
  161. * @param key
  162. * @return
  163. */
  164. public Object lPop(String key) {
  165. ListOperations<String, Object> list = redisTemplate.opsForList();
  166. return list.leftPop(key);
  167. }
  168. /**
  169. * 右弹出数列
  170. * @param key
  171. * @return
  172. */
  173. public Object rPop(String key) {
  174. ListOperations<String, Object> list = redisTemplate.opsForList();
  175. return list.rightPop(key);
  176. }
  177. /**
  178. * 列表获取
  179. *
  180. * @param k
  181. * @param l
  182. * @param l1
  183. * @return
  184. */
  185. public List<Object> lRange(String k, long l, long l1) {
  186. ListOperations<String, Object> list = redisTemplate.opsForList();
  187. return list.range(k, l, l1);
  188. }
  189. /**
  190. * 列表获取
  191. * @param key
  192. * @return
  193. */
  194. public List<Object> lRange(String key){
  195. ListOperations<String, Object> list = redisTemplate.opsForList();
  196. return list.range(key, 0, list.size(key));
  197. }
  198. /**
  199. * 集合添加
  200. *
  201. * @param key
  202. * @param value
  203. */
  204. public void add(String key, Object value) {
  205. SetOperations<String, Object> set = redisTemplate.opsForSet();
  206. set.add(key, value);
  207. }
  208. /**
  209. * 集合获取
  210. *
  211. * @param key
  212. * @return
  213. */
  214. public Set<Object> setMembers(String key) {
  215. SetOperations<String, Object> set = redisTemplate.opsForSet();
  216. return set.members(key);
  217. }
  218. /**
  219. * 有序集合添加
  220. *
  221. * @param key
  222. * @param value
  223. * @param scoure
  224. */
  225. public void zAdd(String key, Object value, double scoure) {
  226. ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
  227. zset.add(key, value, scoure);
  228. }
  229. /**
  230. * 有序集合获取
  231. *
  232. * @param key
  233. * @param scoure
  234. * @param scoure1
  235. * @return
  236. */
  237. public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
  238. ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
  239. redisTemplate.opsForValue();
  240. return zset.rangeByScore(key, scoure, scoure1);
  241. }
  242. /**
  243. * 有序集合获取排名
  244. *
  245. * @param key 集合名称
  246. * @param value 值
  247. */
  248. public Long zRank(String key, Object value) {
  249. ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
  250. return zset.rank(key,value);
  251. }
  252. /**
  253. * 有序集合获取排名
  254. *
  255. * @param key
  256. */
  257. public Set<ZSetOperations.TypedTuple<Object>> zRankWithScore(String key, long start,long end) {
  258. ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
  259. Set<ZSetOperations.TypedTuple<Object>> ret = zset.rangeWithScores(key,start,end);
  260. return ret;
  261. }
  262. /**
  263. * 有序集合添加
  264. *
  265. * @param key
  266. * @param value
  267. */
  268. public Double zSetScore(String key, Object value) {
  269. ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
  270. return zset.score(key,value);
  271. }
  272. /**
  273. * 有序集合添加分数
  274. *
  275. * @param key
  276. * @param value
  277. * @param scoure
  278. */
  279. public void incrementScore(String key, Object value, double scoure) {
  280. ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
  281. zset.incrementScore(key, value, scoure);
  282. }
  283. /**
  284. * 有序集合获取排名
  285. *
  286. * @param key
  287. */
  288. public Set<ZSetOperations.TypedTuple<Object>> reverseZRankWithScore(String key, long start,long end) {
  289. ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
  290. Set<ZSetOperations.TypedTuple<Object>> ret = zset.reverseRangeByScoreWithScores(key,start,end);
  291. return ret;
  292. }
  293. /**
  294. * 有序集合获取排名
  295. *
  296. * @param key
  297. */
  298. public Set<ZSetOperations.TypedTuple<Object>> reverseZRankWithRank(String key, long start, long end) {
  299. ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
  300. Set<ZSetOperations.TypedTuple<Object>> ret = zset.reverseRangeWithScores(key, start, end);
  301. return ret;
  302. }
  303. //第一次加载的时候将数据加载到redis中
  304. public void saveDataToRedis(String name) {
  305. double index = Math.abs(name.hashCode() % size);
  306. long indexLong = new Double(index).longValue();
  307. boolean availableUsers = setBit("availableUsers", indexLong, true);
  308. }
  309. //第一次加载的时候将数据加载到redis中
  310. public boolean getDataToRedis(String name) {
  311. double index = Math.abs(name.hashCode() % size);
  312. long indexLong = new Double(index).longValue();
  313. return getBit("availableUsers", indexLong);
  314. }
  315. /**
  316. * 删除对应的value
  317. * @param key
  318. */
  319. /* public boolean remove(final String key) {
  320. if (exists(key)) {
  321. Boolean delete = redisTemplate.delete(key);
  322. return delete;
  323. }
  324. return false;
  325. }*/
  326. }

完毕,
有不对的地方请多多指正。

发表评论

表情:
评论列表 (有 0 条评论,145人围观)

还没有评论,来说两句吧...

相关阅读