目的:解決單機session不能共享問題,插入查詢數據庫時間效率問題,實現分布式緩存。
准備材料:Redis 下載鏈接 http://pan.baidu.com/s/1dEGTxvV
相關jar包如果需要可以留言也可以自行下載
redis 下載之后安裝部署:
解壓壓縮包,第一步點擊run.bat如下圖
############### redis連接池配置
第二步會出現如下圖,有端口號的界面標示啟動成功。
第三步如果發生產時候需要改掉端口號,防止被攻擊,在redis.conf配置文件里面修改
第四步點擊安裝客戶端
安裝好后按如下操作
好了以上就將redis安裝部署完成了,下面需要將其用到我們的項目里面。與spring相結合
准備開始
第一步:
首先需要配置文件,也可以不配置直接在xml中寫,但是為了以后的方便修改,建議寫到配置文件名字命名為redis.properties里面。
############### redis連接池配置
#redis主機地址
redis.host=127.0.0.1
#redis端口
redis.port=6379
#redis連接池最大值
redis.pool.maxTotal=300
#redis連接最大空閑值
redis.pool.maxIdle=20
#redis連接最小空閑值
redis.pool.minIdle=5
#redis獲取連接時是否驗證可用性
redis.pool.testOnBorrow=true
#redis連接超時時間
redis.timeout=15000
#是否使用連接池管理連接
redis.usePool=true
##################### redis管理session #############################
然后配置spring-context-redis.xml也可以直接寫在applicationContext.xml里面但是我這里通過導入的方式
************************spring-context-redis.xml***************** <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.tianrong"> </context:component-scan> <context:component-scan base-package="com.etianrong"> </context:component-scan> <!-- Jedis --> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxTotal" value="${redis.pool.maxTotal}" /> <property name="maxIdle" value="${redis.pool.maxIdle}" /> <property name="minIdle" value="${redis.pool.minIdle}" /> <property name="testOnBorrow" value="${redis.pool.testOnBorrow}" /> </bean> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="${redis.host}" /> <property name="port" value="${redis.port}" /> <property name="timeout" value="${redis.timeout}" /> <property name="usePool" value="${redis.usePool}" /> <property name="poolConfig" ref="jedisPoolConfig" /> </bean> <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" /> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory"/> <property name="keySerializer" ref="stringRedisSerializer"/> <property name="hashKeySerializer" ref="stringRedisSerializer"/> </bean> </beans> ************************spring-context-redis.xml***************** ************************applicationContext.xml***start************* <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>classpath*:*.properties</value> </property> <property name="fileEncoding" value="utf-8" /> </bean> <import resource="spring-context-redis.xml"/>#在這導入 ************************applicationContext.xml***end************* ************************web.xml***start************* <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> ************************web.xml***end*************
**************初始化數據監聽器******Start***********
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.tianrong.product.entity.Integral; import com.tianrong.product.service.IntegralService; import org.springframework.data.redis.core.RedisTemplate; /* * 監聽器,用於項目啟動的時候初始化信息 */ @Service public class StartAddCacheListener implements ApplicationListener<ContextRefreshedEvent> { //日志 private final Logger log= Logger.getLogger(StartAddCacheListener.class); @Autowired public RedisUtil<Object> redisCache; @Override public void onApplicationEvent(ContextRefreshedEvent event) { //初始化數據 redisCache.setCacheObject("dataList", "Hello World!"); } public void test (){ String dataList= redisCache.getCacheObject("dataList"); log.info(dataList+"****************************************"); } } ************************初始化數據監聽器*****end ********************************工具類********************** import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.redis.core.BoundSetOperations; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Service; /** * @author Wolf * */ @Service public class RedisUtil<T> { // @Autowired @Qualifier("redisTemplate") // public RedisTemplate redisTemplate; @Autowired public RedisTemplate redisTemplate; /** * 緩存基本的對象,Integer、String、實體類等 * @param key 緩存的鍵值 * @param value 緩存的值 * @return 緩存的對象 */ public <T> ValueOperations<String,T> setCacheObject(String key,T value) { System.out.println(key+"*****"+value.toString()); ValueOperations<String,T> operation = redisTemplate.opsForValue(); operation.set(key,value); return operation; } /** * 獲得緩存的基本對象。 * @param key 緩存鍵值 * @param operation * @return 緩存鍵值對應的數據 */ public <T> T getCacheObject(String key/*,ValueOperations<String,T> operation*/) { ValueOperations<String,T> operation = redisTemplate.opsForValue(); return operation.get(key); } /** * 緩存List數據 * @param key 緩存的鍵值 * @param dataList 待緩存的List數據 * @return 緩存的對象 */ public <T> ListOperations<String, T> setCacheList(String key,List<T> 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 <T> List<T> getCacheList(String key) { List<T> dataList = new ArrayList<T>(); ListOperations<String,T> 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 <T> BoundSetOperations<String,T> setCacheSet(String key,Set<T> dataSet) { BoundSetOperations<String,T> setOperation = redisTemplate.boundSetOps(key); /*T[] t = (T[]) dataSet.toArray(); setOperation.add(t);*/ Iterator<T> it = dataSet.iterator(); while(it.hasNext()) { setOperation.add(it.next()); } return setOperation; } /** * 獲得緩存的set * @param key * @param operation * @return */ public Set<T> getCacheSet(String key/*,BoundSetOperations<String,T> operation*/) { Set<T> dataSet = new HashSet<T>(); BoundSetOperations<String,T> 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 <T> HashOperations<String,String,T> setCacheMap(String key,Map<String,T> dataMap) { HashOperations hashOperations = redisTemplate.opsForHash(); if(null != dataMap) { for (Map.Entry<String, T> 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 <T> Map<String,T> getCacheMap(String key/*,HashOperations<String,String,T> hashOperation*/) { Map<String, T> map = redisTemplate.opsForHash().entries(key); /*Map<String, T> map = hashOperation.entries(key);*/ return map; } /** * 緩存Map * @param key * @param dataMap * @return */ public <T> HashOperations<String,Integer,T> setCacheIntegerMap(String key,Map<Integer,T> dataMap) { HashOperations hashOperations = redisTemplate.opsForHash(); if(null != dataMap) { for (Map.Entry<Integer, T> 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 <T> Map<Integer,T> getCacheIntegerMap(String key/*,HashOperations<String,String,T> hashOperation*/) { Map<Integer, T> map = redisTemplate.opsForHash().entries(key); /*Map<String, T> map = hashOperation.entries(key);*/ return map; } } **************************************工具類**************************
下面是初始化監聽器效果圖************
以下是單元測試圖