目的:解决单机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;
} }
**************************************工具类**************************

下面是初始化监听器效果图************ 
 
以下是单元测试图 

组件-------(一)redis系列--安装部署redis+实现redis分布式缓存 java+Spring+redis的更多相关文章

  1. redis的安装部署启动停止<17.3.21已更新>

    --------------------------------------------------------- 启动redis时使用下面两条命令: redis-server /etc/redis. ...

  2. Redis- 内存数据库Redis之安装部署

    内存数据库Redis之安装部署 Redis是一款非关系型,key-value存储的内存数据库,Redis数据库完全在内存中,使用磁盘仅用于持久性.Redis的速度非常快,每秒能执行约11万集合,每秒约 ...

  3. 如何用分布式缓存服务实现Redis内存优化

    Redis是一种支持Key-Value等多种数据结构的存储系统,其数据特性是“ALL IN MEMORY”,因此优化内存十分重要.在对Redis进行内存优化时,先要掌握Redis内存存储的特性比如字符 ...

  4. redis cluster安装部署(测试环境)

    redis 应用于web前端,做缓存和数据存取的速度是挺可观的,最近看了一些资料,手痒了,就弄了一个测试环境,两台方案,试用一下. ##Redis 集群部署## 一,方案调研: 参考博客: http: ...

  5. windows环境redis主从安装部署

    准备工作 下载windows环境redis,我下载的是2.4.5,解压,拷贝一主(master)两从(slaveof).主机端口使用6379,两从的端口分别为6380和6381, 我本地索性用6379 ...

  6. Redis系列之(一):10分钟玩转Redis(转)

    1. Redis介绍 Redis是一个开源的使用ANSI C语言编写.基于内存的Key-Value数据库. 它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集 ...

  7. Redis系列之(一):10分钟玩转Redis

    1. Redis介绍 Redis是一个开源的使用ANSI C语言编写.基于内存的Key-Value数据库. 它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集 ...

  8. Redis 学习-安装、数据类型与 API 理解、Java 客户端

    本博客是在学习<Redis从入门到高可用,分布式实践>教程时的笔记. 同时参考: https://www.cnblogs.com/jiang910/p/10020048.html 一.Re ...

  9. 第十二节:Asp.Net Core 之分布式缓存(SQLServer和Redis)

    一. 整体说明 1. 说明 分布式缓存通常是指在多个应用程序服务器的架构下,作为他们共享的外部服务共享缓存,常用的有SQLServer.Redis.NCache.     特别说明一下:这里的分布式是 ...

随机推荐

  1. Winform - TreeView控件,只展开根目录

    TreeNode类型是有Expand和ExpandAll这两个方法.而Treeview是只有ExpandAll的,想要展开根目录下面的节点的话 //只展开根目录 ) ].Expand();

  2. Linux主机上发布java web应用

    1.链接远程主机命令 ssh user@hostname 如: shh root@192.168.1.1 2.查看主机操作系统版本 uname -a 3.linux系统安装mysql a)检查是否安装 ...

  3. SQL Server使用问题总结

    1.datetime,smalldatetime,date的区别 1)datetime 从1753年1月1日到9999年12月31日的日期和时间数据,精确度为百分之三秒(等于   3.33毫秒或0.0 ...

  4. css 水平居中的办法

    <div style="width: 100%; text-align: center; margin: auto;"> <div style="dis ...

  5. Swift - 通过url地址打开web页面

    通过UIApplication.sharedApplication().openURL()方法,可以使用浏览器打开相应的网页. 1 2 3 var urlString = "http://h ...

  6. Servlet的学习(三)

    本篇接上一篇<Servlet的学习(二)> ,主要讲诉如何使用MyEclipse来开发Servlet,和导入Servlet所需要的源代码. 现在我们来创建一个web应用,就叫[myserv ...

  7. Java基础:泛型及其擦除性、不可协变性

    转载请注明出处:jiq•钦's technical Blog 1泛型语法: 泛型类: class ClassName<T>{} 泛型方法:public <T> void f(T ...

  8. struts2对action中的方法进行输入校验---xml配置方式(3)

    上面两篇文章已经介绍了通过编码java代码的方式实现action方法校验,这里我们介绍第二种方式:xml配置文件 首先我们来看一个样例: ValidateAction.java: package co ...

  9. alv 列标题

    gs_fieldcat-reptext_ddic才是显示列标题的

  10. 【老鸟学算法】包含 min函数的栈设计——java实现

    要求: 1. 定义栈的数据结构,要求添加一个 min函数,能够得到栈的最小元素. 2. 要求函数 min.push 以及 pop 的时间复杂度都是 O(1). 这是考验“栈”数据结构设计.众所周知,栈 ...