设为首页 收藏本站
查看: 993|回复: 0

[经验分享] spring + redis 实现数据的缓存

[复制链接]

尚未签到

发表于 2017-12-20 21:57:04 | 显示全部楼层 |阅读模式
1)、配置的文件(properties)
  将那些经常要变化的参数配置成独立的propertis,方便以后的修改
  redis.properties



1 redis.hostName=127.0.0.1
2 redis.port=6379
3 redis.timeout=15000
4 redis.usePool=true
5
6 redis.maxIdle=6
7 redis.minEvictableIdleTimeMillis=300000
8 redis.numTestsPerEvictionRun=3
9 redis.timeBetweenEvictionRunsMillis=60000

2)、spring-redis.xml
  redis的相关参数配置设置。参数的值来自上面的properties文件



1 <beans xmlns="http://www.springframework.org/schema/beans"  
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" default-autowire="byName">  
4     <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  
5         <!-- <property name="maxIdle" value="6"></property>  
6         <property name="minEvictableIdleTimeMillis" value="300000"></property>  
7         <property name="numTestsPerEvictionRun" value="3"></property>  
8         <property name="timeBetweenEvictionRunsMillis" value="60000"></property>   -->
9  
10         <property name="maxIdle" value="${redis.maxIdle}"></property>  
11         <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"></property>  
12         <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"></property>  
13         <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"></property>
14     </bean>  
15     <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy">  
16         <property name="poolConfig" ref="jedisPoolConfig"></property>  
17         <property name="hostName" value="${redis.hostName}"></property>  
18         <property name="port" value="${redis.port}"></property>  
19         <property name="timeout" value="${redis.timeout}"></property>  
20         <property name="usePool" value="${redis.usePool}"></property>  
21     </bean>  
22     <bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">  
23         <property name="connectionFactory" ref="jedisConnectionFactory"></property>  
24         <property name="keySerializer">  
25             <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>  
26         </property>  
27         <property name="valueSerializer">  
28             <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>  
29         </property>  
30     </bean>  
31 </beans>

3)、applicationContext.xml
  spring的总配置文件,在里面假如一下的代码



1 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
2         <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
3         <property name="ignoreResourceNotFound" value="true" />
4         <property name="locations">
5             <list>
6  
7                 <value>classpath*:/META-INF/config/redis.properties</value>
8             </list>
9         </property>
10     </bean>
11  
12 <import resource="spring-redis.xml" />

4)、web.xml
  设置spring的总配置文件在项目启动时加载



1 <context-param>
2     <param-name>contextConfigLocation</param-name>
3     <param-value>classpath*:/META-INF/applicationContext.xml</param-value><!--  -->
4 </context-param>

5)、redis缓存工具类
  ValueOperations  ——基本数据类型和实体类的缓存
ListOperations     ——list的缓存
SetOperations    ——set的缓存
  HashOperations  Map的缓存





  1 import java.io.Serializable;
  2 import java.util.ArrayList;
  3 import java.util.HashMap;
  4 import java.util.HashSet;
  5 import java.util.Iterator;
  6 import java.util.List;
  7 import java.util.Map;
  8 import java.util.Set;
  9  
10 import org.springframework.beans.factory.annotation.Autowired;
11 import org.springframework.beans.factory.annotation.Qualifier;
12 import org.springframework.context.support.ClassPathXmlApplicationContext;
13 import org.springframework.data.redis.core.BoundSetOperations;
14 import org.springframework.data.redis.core.HashOperations;
15 import org.springframework.data.redis.core.ListOperations;
16 import org.springframework.data.redis.core.RedisTemplate;
17 import org.springframework.data.redis.core.SetOperations;
18 import org.springframework.data.redis.core.ValueOperations;
19 import org.springframework.stereotype.Service;
20  
21 @Service
22 public class RedisCacheUtil<T>
23 {
24  
25     @Autowired @Qualifier("jedisTemplate")
26     public RedisTemplate redisTemplate;
27  
28     /**
29      * 缓存基本的对象,Integer、String、实体类等
30      * @param key    缓存的键值
31      * @param value    缓存的值
32      * @return        缓存的对象
33      */
34     public <T> ValueOperations<String,T> setCacheObject(String key,T value)
35     {
36  
37         ValueOperations<String,T> operation = redisTemplate.opsForValue();
38         operation.set(key,value);
39         return operation;
40     }
41  
42     /**
43      * 获得缓存的基本对象。
44      * @param key        缓存键值
45      * @param operation
46      * @return            缓存键值对应的数据
47      */
48     public <T> T getCacheObject(String key/*,ValueOperations<String,T> operation*/)
49     {
50         ValueOperations<String,T> operation = redisTemplate.opsForValue();
51         return operation.get(key);
52     }
53  
54     /**
55      * 缓存List数据
56      * @param key        缓存的键值
57      * @param dataList    待缓存的List数据
58      * @return            缓存的对象
59      */
60     public <T> ListOperations<String, T> setCacheList(String key,List<T> dataList)
61     {
62         ListOperations listOperation = redisTemplate.opsForList();
63         if(null != dataList)
64         {
65             int size = dataList.size();
66             for(int i = 0; i < size ; i ++)
67             {
68  
69                 listOperation.rightPush(key,dataList.get(i));
70             }
71         }
72  
73         return listOperation;
74     }
75  
76     /**
77      * 获得缓存的list对象
78      * @param key    缓存的键值
79      * @return        缓存键值对应的数据
80      */
81     public <T> List<T> getCacheList(String key)
82     {
83         List<T> dataList = new ArrayList<T>();
84         ListOperations<String,T> listOperation = redisTemplate.opsForList();
85         Long size = listOperation.size(key);
86  
87         for(int i = 0 ; i < size ; i ++)
88         {
89             dataList.add((T) listOperation.leftPop(key));
90         }
91  
92         return dataList;
93     }
94  
95     /**
96      * 缓存Set
97      * @param key        缓存键值
98      * @param dataSet    缓存的数据
99      * @return            缓存数据的对象
100      */
101     public <T> BoundSetOperations<String,T> setCacheSet(String key,Set<T> dataSet)
102     {
103         BoundSetOperations<String,T> setOperation = redisTemplate.boundSetOps(key);   
104         /*T[] t = (T[]) dataSet.toArray();
105              setOperation.add(t);*/
106  
107         Iterator<T> it = dataSet.iterator();
108         while(it.hasNext())
109         {
110             setOperation.add(it.next());
111         }
112  
113         return setOperation;
114     }
115  
116     /**
117      * 获得缓存的set
118      * @param key
119      * @param operation
120      * @return
121      */
122     public Set<T> getCacheSet(String key/*,BoundSetOperations<String,T> operation*/)
123     {
124         Set<T> dataSet = new HashSet<T>();
125         BoundSetOperations<String,T> operation = redisTemplate.boundSetOps(key);   
126  
127         Long size = operation.size();
128         for(int i = 0 ; i < size ; i++)
129         {
130             dataSet.add(operation.pop());
131         }
132         return dataSet;
133     }
134  
135     /**
136      * 缓存Map
137      * @param key
138      * @param dataMap
139      * @return
140      */
141     public <T> HashOperations<String,String,T> setCacheMap(String key,Map<String,T> dataMap)
142     {
143  
144         HashOperations hashOperations = redisTemplate.opsForHash();
145         if(null != dataMap)
146         {
147  
148             for (Map.Entry<String, T> entry : dataMap.entrySet()) {  
149  
150                 /*System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  */
151                 hashOperations.put(key,entry.getKey(),entry.getValue());
152             }
153  
154         }
155  
156         return hashOperations;
157     }
158  
159     /**
160      * 获得缓存的Map
161      * @param key
162      * @param hashOperation
163      * @return
164      */
165     public <T> Map<String,T> getCacheMap(String key/*,HashOperations<String,String,T> hashOperation*/)
166     {
167         Map<String, T> map = redisTemplate.opsForHash().entries(key);
168         /*Map<String, T> map = hashOperation.entries(key);*/
169         return map;
170     }
171  
172     /**
173      * 缓存Map
174      * @param key
175      * @param dataMap
176      * @return
177      */
178     public <T> HashOperations<String,Integer,T> setCacheIntegerMap(String key,Map<Integer,T> dataMap)
179     {
180         HashOperations hashOperations = redisTemplate.opsForHash();
181         if(null != dataMap)
182         {
183  
184             for (Map.Entry<Integer, T> entry : dataMap.entrySet()) {  
185  
186                 /*System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  */
187                 hashOperations.put(key,entry.getKey(),entry.getValue());
188             }
189  
190         }
191  
192         return hashOperations;
193     }
194  
195     /**
196      * 获得缓存的Map
197      * @param key
198      * @param hashOperation
199      * @return
200      */
201     public <T> Map<Integer,T> getCacheIntegerMap(String key/*,HashOperations<String,String,T> hashOperation*/)
202     {
203         Map<Integer, T> map = redisTemplate.opsForHash().entries(key);
204         /*Map<String, T> map = hashOperation.entries(key);*/
205         return map;
206     }
207 }

6)、测试
  这里测试我是在项目启动的时候到数据库中查找出国家和城市的数据,进行缓存,之后将数据去出
  6.1  项目启动时缓存数据



import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import com.test.model.City;
import com.test.model.Country;
import com.zcr.test.User;
/*
* 监听器,用于项目启动的时候初始化信息
*/
@Service
public class StartAddCacheListener implements ApplicationListener<ContextRefreshedEvent>
{
//日志
private final Logger log= Logger.getLogger(StartAddCacheListener.class);
@Autowired
private RedisCacheUtil<Object> redisCache;
@Autowired
private BrandStoreService brandStoreService;
@Override
public void onApplicationEvent(ContextRefreshedEvent  event)
{
//spring 启动的时候缓存城市和国家等信息
if(event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext"))
{
System.out.println("\n\n\n_________\n\n缓存数据 \n\n ________\n\n\n\n");
List<City> cityList = brandStoreService.selectAllCityMessage();
List<Country> countryList = brandStoreService.selectAllCountryMessage();
Map<Integer,City> cityMap = new HashMap<Integer,City>();
Map<Integer,Country> countryMap = new HashMap<Integer, Country>();
int cityListSize = cityList.size();
int countryListSize = countryList.size();
for(int i = 0 ; i < cityListSize ; i ++ )
{
cityMap.put(cityList.get(i).getCity_id(), cityList.get(i));
}
for(int i = 0 ; i < countryListSize ; i ++ )
{
countryMap.put(countryList.get(i).getCountry_id(), countryList.get(i));
}
redisCache.setCacheIntegerMap("cityMap", cityMap);
redisCache.setCacheIntegerMap("countryMap", countryMap);
}
}
}
  6.2  获取缓存数据



1 @Autowired
2     private RedisCacheUtil<User> redisCache;
3  
4     @RequestMapping("testGetCache")
5     public void testGetCache()
6     {
7         /*Map<String,Country> countryMap = redisCacheUtil1.getCacheMap("country");
8         Map<String,City> cityMap = redisCacheUtil.getCacheMap("city");*/
9         Map<Integer,Country> countryMap = redisCacheUtil1.getCacheIntegerMap("countryMap");
10         Map<Integer,City> cityMap = redisCacheUtil.getCacheIntegerMap("cityMap");
11  
12         for(int key : countryMap.keySet())
13         {
14             System.out.println("key = " + key + ",value=" + countryMap.get(key));
15         }
16  
17         System.out.println("------------city");
18         for(int key : cityMap.keySet())
19         {
20             System.out.println("key = " + key + ",value=" + cityMap.get(key));
21         }
22     }
  由于Spring在配置文件中配置的bean默认是单例的,所以只需要通过Autowired注入,即可得到原先的缓存类。
  原文:http://www.cnblogs.com/0201zcr/p/4987561.html

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-426237-1-1.html 上篇帖子: [redis] 几种redis数据导出导入方式 下篇帖子: ehcache memcache redis 区别
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表