目的:解决单机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; } } **************************************工具类**************************
下面是初始化监听器效果图************
以下是单元测试图
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/19455.html