Spring + Jedis集成Redis(单例redis数据库)
这几天没事,就把之前学习的redis代码整理一遍,废话不多说,上步骤。
1、pom.xml引入资源;
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.0.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
2、配置redis的配置文件,这里只配置单点数据库,后面会介绍redis集群的配置,这里就不多说了;
spring-redis.xml配置:
<!-- 读取配置文件信息 -->
<context:property-placeholder ignore-unresolvable="true" location="classpath:*.properties"/> <!-- Redis 配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.maxActive}" />
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
<property name="testOnBorrow" value="true" />
</bean> <!-- redis单节点数据库连接配置 -->
<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="password" value="${redis.password}" />
<property name="poolConfig" ref="jedisPoolConfig" />
</bean> <!-- redisTemplate配置,redisTemplate是对Jedis的对redis操作的扩展,有更多的操作,封装使操作更便捷 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
</bean>
redis.properties文件配置:
#redis的服务器地址
redis.host=这里写你的ip
#redis的服务端口
redis.port=6379
#密码
redis.password=这里写你的密码
#链接数据库
redis.default.db=0
#客户端超时时间单位是毫秒
redis.timeout=100000
#最大连接数
redis.maxActive=300
#最大空闲数
redis.maxIdle=100
#最大建立连接等待时间
redis.maxWaitMillis=1000
3、接着,具体实现代码;
序列化和反序列化工具类:
public class SerializerUtil {
/**
* 序列化
* @param object
* @return
*/
public static byte[] serializeObj(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
} catch (Exception e) {
throw new RuntimeException("序列化失败!", e);
}
}
/**
* 反序列化
* @param bytes
* @return
*/
public static Object deserializeObj(byte[] bytes) {
if (bytes == null){
return null;
}
ByteArrayInputStream bais = null;
try {
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
throw new RuntimeException("反序列化失败!", e);
}
}
}
操作实现类,这里只提供了3个实现方法,其他的可以按照自己需求自己实现:
@Component
public class RedisCache { @Resource
private RedisTemplate<String, String> redisTemplate; /**
* 添加缓存数据
* @param key
* @param obj
* @param <T>
* @return
* @throws Exception
*/
public <T> boolean putCache(String key, T obj) throws Exception {
final byte[] bkey = key.getBytes();
final byte[] bvalue = SerializerUtil.serializeObj(obj);
boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
return connection.setNX(bkey, bvalue);
}
});
return result;
} /**
* 添加缓存数据,设定缓存失效时间
* @param key
* @param obj
* @param expireTime
* @param <T>
* @throws Exception
*/
public <T> void putCacheWithExpireTime(String key, T obj, final long expireTime) throws Exception {
final byte[] bkey = key.getBytes();
final byte[] bvalue = SerializerUtil.serializeObj(obj);
redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
connection.setEx(bkey, expireTime, bvalue);
return true;
}
});
} /**
* 根据key取缓存数据
* @param key
* @param <T>
* @return
* @throws Exception
*/
public <T> T getCache(final String key) throws Exception {
byte[] result = redisTemplate.execute(new RedisCallback<byte[]>() {
@Override
public byte[] doInRedis(RedisConnection connection) throws DataAccessException {
return connection.get(key.getBytes());
}
});
if (result == null) {
return null;
}
return (T) SerializerUtil.deserializeObj(result);
}
}
4、测试代码;
@Test
public void test7() throws Exception{
List<String> list = new ArrayList<String>();
list.add("测试list");
list.add("测试list2"); Map<String,Object> map = new HashMap<String, Object>();
map.put("test*","测试数据");
map.put("测试数据","啥的");
map.put("listTest",list);
redisCache.putCache("testMap",map); Map<String,Object> mapResult = redisCache.getCache("testMap");
System.out.print(mapResult.toString()); }
结果:

5、OK,一切正常。ps:有兴趣的同学可以去看看redis源码,挺好!
Spring + Jedis集成Redis(单例redis数据库)的更多相关文章
- Spring + Jedis集成Redis(集群redis数据库)
前段时间说过单例redis数据库的方法,但是生成环境一般不会使用,基本上都是集群redis数据库,所以这里说说集群redis的代码. 1.pom.xml引入jar <!--Redis--> ...
- Redis 单例、主从模式、sentinel 以及集群的配置方式及优缺点对比(转)
摘要: redis作为一种NoSql数据库,其提供了一种高效的缓存方案,本文则主要对其单例,主从模式,sentinel以及集群的配置方式进行说明,对比其优缺点,阐述redis作为一种缓存框架的高可用性 ...
- ThinkPHP5+Redis单例型购物车
<?php /** * Redis + 单例型购物车 * param $basket 存储商品信息 * param $ins 存储实例化对象 */ namespace lib; use redi ...
- Spring容器-ApplicationContext的单例设计
Spring容器-ApplicationContext的单例设计 每次通过new创建一个ApplicationContext容器,都会执行refresh方法,看源代码了解到这个refresh方法会 ...
- SSM-Spring-05:Spring的bean是单例还是多例,怎么改变?
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- Spring的bean是单例的 它在Spring容器初始化的时候创建对象 可以修改为多例,在此bean节点中添 ...
- 【Spring】8、Spring框架中的单例Beans是线程安全的么
看到这样一个问题:spring框架中的单例Beans是线程安全的么? Spring框架并没有对单例bean进行任何多线程的封装处理.关于单例bean的线程安全和并发问题需要开发者自行去搞定.但实际上, ...
- Spring5源码解析-Spring框架中的单例和原型bean
Spring5源码解析-Spring框架中的单例和原型bean 最近一直有问我单例和原型bean的一些原理性问题,这里就开一篇来说说的 通过Spring中的依赖注入极大方便了我们的开发.在xml通过& ...
- Spring 的Controller 是单例or多例
Spring 的Controller 是单例or多例 你什么也不肯放弃,又得到了什么? 背景:今天写代码遇到一个Controller 中的线程安全问题,那么Spring 的Controller 是单例 ...
- Spring框架中的单例bean是线程安全的吗?
不,Spring框架中的单例bean不是线程安全的.
- Spring 框架中的单例 bean 是线程安全的吗?
不,Spring 框架中的单例 bean 不是线程安全的.
随机推荐
- CCPC2016杭州现场赛
A(hdu5933):(贪心) 题意:长度为n的数组: a1, a2,⋯, 每次操作要么可以merge两个相邻的数为一个, 值为两个数的和; 要么可以把一个数分裂成两个, 两个数的和为原数. 用最少的 ...
- 【转】js实现复制到剪贴板功能,兼容所有浏览器
两天前听了一个H5的分享,会议上有一句话,非常有感触:不是你不能,而是你对自己的要求太低.很简单的一句话,相信很多事情不是大家做不到,真的是对自己的要求太低,如果对自己要求多一点,那么你取得的进步可能 ...
- C++ 一个例子彻底搞清楚拷贝构造函数和赋值运算符重载的区别
class TestChild { public: TestChild() { x=; y=; printf("TestChild: Constructor be called!\n&quo ...
- Advanced Office Password Recovery安装后显示是英文版的
一些才开始接触Advanced Office Password Recovery(即AOPR)的朋友,在安装Advanced Office Password Recovery的时候可能发现Advanc ...
- Web jquery表格组件 JQGrid 的使用 - 7.查询数据、编辑数据、删除数据
系列索引 Web jquery表格组件 JQGrid 的使用 - 从入门到精通 开篇及索引 Web jquery表格组件 JQGrid 的使用 - 4.JQGrid参数.ColModel API.事件 ...
- DiskFileItemFactory类的使用
将请求消息实体中的每一个项目封装成单独的DiskFileItem (FileItem接口的实现) 对象的任务由 org.apache.commons.fileupload.FileItemFact ...
- 浅谈Android中layout_weight
引言 在开发android过程中,我们经常需要对界面进行按比例进行布局,我们一般都会使用layout_属性来进行设置.今天这篇文章我们就来简单介绍下layout_weight的使用和布局原理.随着做项 ...
- 深入理解IoC/DI
------------------------------------------------------------------------ 理解IoC/DI 1.控制反转 --> 谁控制谁 ...
- hadoop集群安装_实战
spark1.6.2+ hadoop2.6.2 词频统计完整案例:http://blog.csdn.net/zythy/article/details/17852579 hadoop学习:http:/ ...
- 《UNIX网络编程(第3版)》unp.h等源码文件的编译安装
操作系统:Mac OS X 10.11.5 1.下载书中的源代码:点击下载 2.切换到解压后的目录 unpv13e,先查看下 README,依次执行: ./configure cd lib make ...