spring集成redis

亦凉 2022-05-28 23:44 257阅读 0赞
  1. sprig集成redis,我的项目架构是springMVC+spring+ibatis maven管理 ,下面看代码

1. 在pom文件引入redis依赖包

  1. <!-- redis集成spring -->
  2. <dependency>
  3. <groupId>org.springframework.data</groupId>
  4. <artifactId>spring-data-redis</artifactId>
  5. <version>1.4.2.RELEASE</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>redis.clients</groupId>
  9. <artifactId>jedis</artifactId>
  10. <version>2.6.2</version>
  11. </dependency>

2.redis配置文件applicationContext-redis.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:p="http://www.springframework.org/schema/p"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
  9. default-autowire="byName" >
  10. <context:property-placeholder location="classpath*:/conf/redis.properties" ignore-unresolvable="true"/>
  11. <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
  12. <property name="maxIdle" value="${redis.maxIdle}" />
  13. <property name="maxTotal" value="${redis.maxActive}" />
  14. <property name="maxWaitMillis" value="${redis.maxWait}" />
  15. <property name="testOnBorrow" value="${redis.testOnBorrow}" />
  16. </bean>
  17. <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
  18. <property name="hostName" value="${redis.host}" />
  19. <property name="port" value="${redis.port}" />
  20. <property name="password" value="${redis.pass}" />
  21. <property name="poolConfig" ref="poolConfig" />
  22. </bean>
  23. <bean id="stringSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
  24. <!-- 开启事务,可以通过transcational注解控制 -->
  25. <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
  26. <property name="connectionFactory" ref="connectionFactory" />
  27. <property name="keySerializer" ref="stringSerializer" />
  28. <property name="enableTransactionSupport" value="true" />
  29. </bean>
  30. </beans>

3.redis.properties配置文件

  1. redis.host=redis地址
  2. redis.pass=密码
  3. redis.port=6379
  4. redis.maxIdle=300
  5. redis.maxActive=300
  6. redis.maxTotal=600
  7. redis.maxWait=1000
  8. redis.testOnBorrow=true

4. applicationContext.xml配置文件

在项目启动的时候会加载applicationContext-redis.xml文件,但是redis.properties需要配置,如下

  1. <bean id="config"
  2. class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  3. <property name="locations">
  4. <list>
  5. <value>classpath:/conf/db_mysql.properties</value>
  6. <value>classpath:/conf/redis.properties</value>
  7. </list>
  8. </property>
  9. </bean>

5. 创建RedisService工具类,方便调用

  1. package com.base.redis;
  2. import java.io.UnsupportedEncodingException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.Map;
  6. import java.util.Set;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.dao.DataAccessException;
  11. import org.springframework.data.redis.connection.RedisConnection;
  12. import org.springframework.data.redis.core.RedisCallback;
  13. import org.springframework.data.redis.core.RedisTemplate;
  14. import org.springframework.data.redis.serializer.JacksonJsonRedisSerializer;
  15. import org.springframework.stereotype.Service;
  16. import com.base.utils.StringUtils;
  17. @Service
  18. public class RedisService {
  19. private Logger LOG = LoggerFactory.getLogger(RedisService.class);
  20. @Autowired
  21. private List<RedisTemplate<String, String>> redisTemplateList;
  22. @Autowired
  23. private RedisTemplate<String, String> redisTemplate;
  24. /**
  25. * 从缓存中删除指定的key
  26. * @param keys
  27. */
  28. public void del(final String... keys) {
  29. for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
  30. try {
  31. redisTemplate.execute(new RedisCallback<Long>() {
  32. public Long doInRedis(RedisConnection connection) throws DataAccessException {
  33. long result = 0;
  34. for (int i = 0; i < keys.length; i++) {
  35. result = connection.del(keys[i].getBytes());
  36. }
  37. return result;
  38. }
  39. });
  40. } catch (Exception e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. }
  45. /**
  46. * 重缓存中删除指定的key 模式匹配,效率低
  47. * @param keys
  48. */
  49. public void delByReg(final String... keys) {
  50. for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
  51. try {
  52. redisTemplate.execute(new RedisCallback<Long>() {
  53. public Long doInRedis(RedisConnection connection) throws DataAccessException {
  54. long result = 0;
  55. for (int i = 0; i < keys.length; i++) {
  56. Set<byte[]> keyset = connection.keys((keys[i] + "*").getBytes());
  57. for (byte[] key : keyset) {
  58. result = connection.del(key);
  59. }
  60. }
  61. return result;
  62. }
  63. });
  64. } catch (Exception e) {
  65. e.printStackTrace();
  66. }
  67. }
  68. }
  69. /**
  70. * 判断一个键是否存在于缓存中
  71. * @param key
  72. * @return
  73. */
  74. public boolean exists(final String key) {
  75. Boolean result = false;
  76. for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
  77. try {
  78. result = (Boolean) redisTemplate.execute(new RedisCallback<Object>() {
  79. public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
  80. return connection.exists(key.getBytes());
  81. }
  82. });
  83. if (result) {
  84. break;
  85. }
  86. } catch (Exception e) {
  87. e.printStackTrace();
  88. }
  89. }
  90. return result;
  91. }
  92. /**
  93. * 向缓存中插入数据
  94. * @param key
  95. * @param value
  96. * @param liveTime
  97. */
  98. public void set(final byte[] key, final byte[] value, final long liveTime) {
  99. for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
  100. try {
  101. redisTemplate.execute(new RedisCallback<Object>() {
  102. public Long doInRedis(final RedisConnection connection) throws DataAccessException {
  103. connection.set(key, value);
  104. if (liveTime > 0) {
  105. connection.expire(key, liveTime);
  106. }
  107. return 1L;
  108. }
  109. });
  110. } catch (Exception e) {
  111. e.printStackTrace();
  112. }
  113. }
  114. }
  115. public <T> void set(String key, T value, long liveTime, Class<T> type) {
  116. if (value == null)
  117. return;
  118. try {
  119. JacksonJsonRedisSerializer<T> serializer = new JacksonJsonRedisSerializer<T>(type);
  120. byte[] _value = serializer.serialize(value);
  121. this.set(key.getBytes(), _value, liveTime);
  122. } catch (Exception e) {
  123. e.printStackTrace();
  124. }
  125. }
  126. public void set(String key, String value, long liveTime) {
  127. try {
  128. this.set(key.getBytes(), value.getBytes("UTF-8"), liveTime);
  129. } catch (UnsupportedEncodingException e) {
  130. e.printStackTrace();
  131. }
  132. }
  133. public <T> List<T> lRange(final String key, final Long begin, final Long end, final Class<T> type) {
  134. return redisTemplate.execute(new RedisCallback<List<T>>() {
  135. public List<T> doInRedis(RedisConnection connection) throws DataAccessException {
  136. JacksonJsonRedisSerializer<T> serializer = new JacksonJsonRedisSerializer<T>(type);
  137. List<T> list = new ArrayList<T>();
  138. for (byte[] element : connection.lRange(key.getBytes(), begin, end)) {
  139. T bean = serializer.deserialize(element);
  140. list.add(bean);
  141. }
  142. return list;
  143. }
  144. });
  145. }
  146. /**
  147. * 从缓存中获取数据
  148. * @param key
  149. * @return
  150. */
  151. public String get(final String key) {
  152. String cacheValue = "";
  153. for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
  154. try {
  155. cacheValue = redisTemplate.execute(new RedisCallback<String>() {
  156. public String doInRedis(RedisConnection connection) throws DataAccessException {
  157. try {
  158. byte[] cacheBytes = connection.get(key.getBytes());
  159. if (cacheBytes != null) {
  160. String cacheStr = new String(cacheBytes, "utf-8");
  161. return cacheStr;
  162. }
  163. } catch (Exception e) {
  164. LOG.info(e.getMessage());
  165. }
  166. return "";
  167. }
  168. });
  169. if (!StringUtils.isEmpty(cacheValue))
  170. break;
  171. } catch (Exception e) {
  172. e.printStackTrace();
  173. }
  174. }
  175. return cacheValue;
  176. }
  177. public <T> T get(final String key, final Class<T> clazz) {
  178. T t = null;
  179. for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
  180. t = redisTemplate.execute(new RedisCallback<T>() {
  181. public T doInRedis(RedisConnection connection) throws DataAccessException {
  182. byte[] data = connection.get(key.getBytes());
  183. if (data != null)
  184. return new JacksonJsonRedisSerializer<T>(clazz).deserialize(data);
  185. return null;
  186. }
  187. });
  188. if (t != null)
  189. break;
  190. }
  191. return t;
  192. }
  193. public <T> Long rPush(final String key, final List<T> list, final Class<T> type, final long expire) {
  194. if (list == null) {
  195. return 0L;
  196. }
  197. return redisTemplate.execute(new RedisCallback<Long>() {
  198. public Long doInRedis(RedisConnection connection) throws DataAccessException {
  199. JacksonJsonRedisSerializer<T> serializer = new JacksonJsonRedisSerializer<T>(type);
  200. connection.multi();
  201. for (T value : list) {
  202. connection.rPush(key.getBytes(), serializer.serialize(value));
  203. }
  204. if (expire > 0) {
  205. connection.expire(key.getBytes(), expire);
  206. }
  207. connection.exec();
  208. return new Long(list.size());
  209. }
  210. });
  211. }
  212. /**
  213. * 清空缓存
  214. */
  215. public void flushDB() {
  216. for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
  217. try {
  218. redisTemplate.execute(new RedisCallback<String>() {
  219. public String doInRedis(RedisConnection connection) throws DataAccessException {
  220. connection.flushDb();
  221. return "ok";
  222. }
  223. });
  224. } catch (Exception e) {
  225. e.printStackTrace();
  226. }
  227. }
  228. }
  229. /**
  230. * 添加至有序集合
  231. * @param key
  232. * @param score
  233. * @param value
  234. */
  235. public void zadd(final byte[] key, final double score, final byte[] value) {
  236. for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
  237. try {
  238. redisTemplate.execute(new RedisCallback<String>() {
  239. public String doInRedis(RedisConnection connection) throws DataAccessException {
  240. connection.zAdd(key, score, value);
  241. return "ok";
  242. }
  243. });
  244. } catch (Exception e) {
  245. e.printStackTrace();
  246. }
  247. }
  248. }
  249. /**
  250. * 按条件获取有序集合元素子集
  251. * @param key
  252. * 有序集合key
  253. * @param min
  254. * 范围最小值
  255. * @param max
  256. * 范围最大值
  257. * @param offset
  258. * 从第0ffset+1个元素起
  259. * @param count
  260. * 返回上限
  261. * @return
  262. */
  263. public Set<byte[]> zRangeByScore(final byte[] key, final double min, final double max, final long offset,
  264. final long count) {
  265. Set<byte[]> set = null;
  266. for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
  267. try {
  268. set = redisTemplate.execute(new RedisCallback<Set<byte[]>>() {
  269. public Set<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
  270. return connection.zRangeByScore(key, min, max, offset, count);
  271. }
  272. });
  273. if (set != null) {
  274. break;
  275. }
  276. } catch (Exception e) {
  277. e.printStackTrace();
  278. }
  279. }
  280. return set;
  281. }
  282. /**
  283. * 添加指定map至缓存
  284. * @param key map唯一标识
  285. * @param hashes
  286. */
  287. @SuppressWarnings({ "unchecked", "rawtypes" })
  288. public void hMSet(final byte[] key, final Map<byte[], byte[]> hashes) {
  289. for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
  290. try {
  291. redisTemplate.execute(new RedisCallback() {
  292. public Object doInRedis(RedisConnection connection) throws DataAccessException {
  293. connection.hMSet(key, hashes);
  294. return null;
  295. }
  296. });
  297. } catch (Exception e) {
  298. e.printStackTrace();
  299. }
  300. }
  301. }
  302. /**
  303. * 获取指定map中指定键对应的值列表
  304. * @param key map的唯一标识
  305. * @param fields 键数组
  306. * @return 值数组
  307. */
  308. public List<byte[]> hMGet(final byte[] key, final byte[]... fields) {
  309. List<byte[]> cacheValue = null;
  310. for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
  311. try {
  312. cacheValue = redisTemplate.execute(new RedisCallback<List<byte[]>>() {
  313. public List<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
  314. return connection.hMGet(key, fields);
  315. }
  316. });
  317. if (cacheValue != null) {
  318. break;
  319. }
  320. } catch (Exception e) {
  321. e.printStackTrace();
  322. }
  323. }
  324. return cacheValue;
  325. }
  326. // getters and setters
  327. public List<RedisTemplate<String, String>> getRedisTemplateList() {
  328. return redisTemplateList;
  329. }
  330. public void setRedisTemplateList(List<RedisTemplate<String, String>> redisTemplateList) {
  331. this.redisTemplateList = redisTemplateList;
  332. }
  333. }

接下来就是调用了,跟普通的service的使用方法是一样的。

发表评论

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

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

相关阅读

    相关 spring集成redis

        sprig集成redis,我的项目架构是springMVC+spring+ibatis 用maven管理 ,下面看代码 1. 在pom文件引入redis依赖包

    相关 Spring集成Redis

    最近在做一个关于群聊的项目,由于聊天要求实时性,不可能直接访问数据库,所以使用了Redis来做缓存,这里将使用过程中遇到的问题记录一下。 使用Redis之前需要合理设计存储