spring + redis 實現資料的緩衝

來源:互聯網
上載者:User

標籤:master   request   null   sel   serial   fresh   修改   項目啟動   磁碟   

 1、實現目標通過redis快取資料。(目的不是加快查詢的速度,而是減少資料庫的負擔)2、所需jar包 注意:jdies和commons-pool兩個jar的版本是有對應關係的,注意引入jar包是要配對使用,否則將會報錯。因為commons-pooljar的目錄根據版本的變化,目錄結構會變。前面的版本是org.apache.pool,而後面的版本是org.apache.pool2…style=” color: white; font-size: 17px; font-weight: bold;”3、redis簡介redis是一個key-value儲存系統。和Memcached類似,它支援儲存的value類型相對更多,包括string(字串)、list(鏈表)、set(集合)、zset(sorted set –有序集合)和hash(雜湊類型)。這些資料類型都支援push/pop、add/remove及取交集並集和差集及更豐富的操作,而且這些操作都是原子性的。在此基礎上,redis支援各種不同方式的排序。與memcached一樣,為了保證效率,資料都是緩衝在記憶體中。區別的是redis會周期性的把更新的資料寫入磁碟或者把修改操作寫入追加的記錄檔案,並且在此基礎上實現了master-slave(主從)4、編碼實現1)、配置的檔案(properties)將那些經常要變化的參數配置成獨立的propertis,方便以後的修改redis.propertiesredis.hostName=127.0.0.1redis.port=6379redis.timeout=15000redis.usePool=trueredis.maxIdle=6redis.minEvictableIdleTimeMillis=300000redis.numTestsPerEvictionRun=3redis.timeBetweenEvictionRunsMillis=600002)、spring-redis.xmlredis的相關參數配置設定。參數的值來自上面的properties檔案 <beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"default-autowire="byName"><beanid="jedisPoolConfig"class="redis.clients.jedis.JedisPoolConfig"><propertyname="maxIdle"value="${redis.maxIdle}">property><propertyname="minEvictableIdleTimeMillis"value="${redis.minEvictableIdleTimeMillis}">property><propertyname="numTestsPerEvictionRun"value="${redis.numTestsPerEvictionRun}">property><propertyname="timeBetweenEvictionRunsMillis"value="${redis.timeBetweenEvictionRunsMillis}">property>bean><beanid="jedisConnectionFactory"class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"destroy-method="destroy"><propertyname="poolConfig"ref="jedisPoolConfig">property><propertyname="hostName"value="${redis.hostName}">property><propertyname="port"value="${redis.port}">property><propertyname="timeout"value="${redis.timeout}">property><propertyname="usePool"value="${redis.usePool}">property>bean><beanid="jedisTemplate"class="org.springframework.data.redis.core.RedisTemplate"><propertyname="connectionFactory"ref="jedisConnectionFactory">property><propertyname="keySerializer"><beanclass="org.springframework.data.redis.serializer.StringRedisSerializer"/>property><propertyname="valueSerializer"><beanclass="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>property>bean>beans>3)、applicationContext.xmlspring的總設定檔,在裡面假如一下的代碼 <beanclass="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><propertyname="systemPropertiesModeName"value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/><propertyname="ignoreResourceNotFound"value="true"/><propertyname="locations"><list><value>classpath*:/META-INF/config/redis.propertiesvalue>list>property>bean><importresource="spring-redis.xml"/>4)、web。xml設定spring的總設定檔在項目啟動時載入<context-param><param-name>contextConfigLocationparam-name><param-value>classpath*:/META-INF/applicationContext.xmlparam-value>context-param>5)、redis緩衝工具類ValueOperations  ——基礎資料型別 (Elementary Data Type)和實體類的緩衝ListOperations   ——list的緩衝SetOperations   ——set的緩衝HashOperations  Map的緩衝importjava.io.Serializable;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.HashSet;importjava.util.Iterator;importjava.util.List;importjava.util.Map;importjava.util.Set;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.context.support.ClassPathXmlApplicationContext;importorg.springframework.data.redis.core.BoundSetOperations;importorg.springframework.data.redis.core.HashOperations;importorg.springframework.data.redis.core.ListOperations;importorg.springframework.data.redis.core.RedisTemplate;importorg.springframework.data.redis.core.SetOperations;importorg.springframework.data.redis.core.ValueOperations;importorg.springframework.stereotype.Service;@ServicepublicclassRedisCacheUtil{@[email protected]("jedisTemplate")publicRedisTemplate redisTemplate;/*** 緩衝基本的對象,Integer、String、實體類等* @param key 緩衝的索引值* @param value 緩衝的值* @return 緩衝的對象*/public ValueOperations setCacheObject(String key,T value){ValueOperations operation = redisTemplate.opsForValue();operation.set(key,value);returnoperation;}/*** 獲得緩衝的基本對象。* @param key 緩衝索引值* @param operation* @return 緩衝索引值對應的資料*/public T getCacheObject(String key/*,ValueOperations operation*/){ValueOperations operation = redisTemplate.opsForValue();return operation.get(key);}/*** 緩衝List資料* @param key 緩衝的索引值* @param dataList 待緩衝的List資料* @return 緩衝的對象*/public ListOperations setCacheList(String key,List dataList){ListOperations listOperation = redisTemplate.opsForList();if(null != dataList){int size = dataList.size();for(int i = 0; i < size ; i ++){listOperation.rightPush(key,dataList.get(i));}}return listOperation;}/*** 獲得緩衝的list對象* @param key 緩衝的索引值* @return 緩衝索引值對應的資料*/public List getCacheList(String key){List dataList = new ArrayList();ListOperations listOperation = redisTemplate.opsForList();Long size = listOperation.size(key);for(int i = 0 ; i < size ; i ++){dataList.add((T) listOperation.leftPop(key));}return dataList;}/*** 緩衝Set* @param key 緩衝索引值* @param dataSet 緩衝的資料* @return 快取資料的對象*/public BoundSetOperations setCacheSet(String key,Set dataSet){BoundSetOperations setOperation = redisTemplate.boundSetOps(key);/*T[] t = (T[]) dataSet.toArray();setOperation.add(t);*/Iterator it = dataSet.iterator();while(it.hasNext()){setOperation.add(it.next());}return setOperation;}/*** 獲得緩衝的set* @param key* @param operation* @return*/public Set getCacheSet(String key/*,BoundSetOperations operation*/){Set dataSet = new HashSet();BoundSetOperations operation = redisTemplate.boundSetOps(key);Long size = operation.size();for(int i = 0 ; i < size ; i++){dataSet.add(operation.pop());}return dataSet;}/*** 緩衝Map* @param key* @param dataMap* @return*/public HashOperations setCacheMap(String key,Map dataMap){HashOperations hashOperations = redisTemplate.opsForHash();if(null != dataMap){for (Map.Entry entry : dataMap.entrySet()) {/*System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); */hashOperations.put(key,entry.getKey(),entry.getValue());}}return hashOperations;}/*** 獲得緩衝的Map* @param key* @param hashOperation* @return*/public Map getCacheMap(String key/*,HashOperations hashOperation*/){Map map = redisTemplate.opsForHash().entries(key);/*Map map = hashOperation.entries(key);*/return map;}/*** 緩衝Map* @param key* @param dataMap* @return*/public HashOperations setCacheIntegerMap(String key,Map dataMap){HashOperations hashOperations = redisTemplate.opsForHash();if(null != dataMap){for (Map.Entry entry : dataMap.entrySet()) {/*System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); */hashOperations.put(key,entry.getKey(),entry.getValue());}}return hashOperations;}/*** 獲得緩衝的Map* @param key* @param hashOperation* @return*/public Map getCacheIntegerMap(String key/*,HashOperations hashOperation*/){Map map = redisTemplate.opsForHash().entries(key);/*Map map = hashOperation.entries(key);*/returnmap;}}6)、測試這裡測試我是在項目啟動的時候到資料庫中尋找出國家和城市的資料,進行緩衝,之後將資料去出6.1 項目啟動時快取資料importjava.util.HashMap;importjava.util.List;importjava.util.Map;importorg.apache.log4j.Logger;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.ApplicationListener;importorg.springframework.context.event.ContextRefreshedEvent;importorg.springframework.stereotype.Service;importcom.test.model.City;importcom.test.model.Country;importcom.zcr.test.User;/** 監聽器,用於項目啟動的時候初始化資訊*/@ServicepublicclassStartAddCacheListener implementsApplicationListener{//日誌privatefinalLogger log= Logger.getLogger(StartAddCacheListener.class);@AutowiredprivateRedisCacheUtil redisCache;@AutowiredprivateBrandStoreService brandStoreService;@OverridepublicvoidonApplicationEvent(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 cityList = brandStoreService.selectAllCityMessage();List countryList = brandStoreService.selectAllCountryMessage();Map cityMap = newHashMap();Map countryMap = newHashMap();intcityListSize = cityList.size();intcountryListSize = countryList.size();for(inti = 0; i < cityListSize ; i ++ ){cityMap.put(cityList.get(i).getCity_id(), cityList.get(i));}for(inti = 0; i < countryListSize ; i ++ ){countryMap.put(countryList.get(i).getCountry_id(), countryList.get(i));}redisCache.setCacheIntegerMap("cityMap", cityMap);redisCache.setCacheIntegerMap("countryMap", countryMap);}}}6.2 擷取快取資料@AutowiredprivateRedisCacheUtil redisCache;@RequestMapping("testGetCache")publicvoidtestGetCache(){/*Map countryMap = redisCacheUtil1.getCacheMap("country");Map cityMap = redisCacheUtil.getCacheMap("city");*/Map countryMap = redisCacheUtil1.getCacheIntegerMap("countryMap");Map cityMap = redisCacheUtil.getCacheIntegerMap("cityMap");for(intkey : countryMap.keySet()){System.out.println("key = "+ key + ",value="+ countryMap.get(key));}System.out.println("------------city");for(intkey : cityMap.keySet()){System.out.println("key = "+ key + ",value="+ cityMap.get(key));}}由於Spring在設定檔中配置的bean預設是單例的,所以只需要通過Autowired注入,即可得到原先的緩衝類。

spring + redis 實現資料的緩衝

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.