Redis和Spring整合
Redis和Spring整合
Redis在这篇里就不做介绍了~以后系统的学学,然后整理写出来。
首先是环境的搭建
通过自己引包的方式,将redis和spring-redis的包引到自己的项目中,我项目中是通过pom引进的,如下(貌似版本都是写着篇博客时最新的):
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.1.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
通过pom的依赖可以看出来,我用的Jedis作为我的Cilent。
配置Spring的配置文件
现在spring-boot框架大火,但是目前,我还是为了项目的可读性,使用配置文件的方式进行配置。以后有机会学习一下注解的方式,在总结出来。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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">
<!-- 引入参数文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:init.properties</value>
</property>
</bean>
<!-- 使用redis缓存 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxTotal" value="${redis.maxActive}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="true" />
</bean>
<bean id="jedis.shardInfo1" class="redis.clients.jedis.JedisShardInfo">
<constructor-arg index="0" value="${redis.host}" />
<constructor-arg index="1" value="${redis.port}" />
<constructor-arg index="2" value="${redis.timeout}" />
<constructor-arg index="3" value="${redis.default.db}" />
<property name="password" value="${redis.pass}"></property>
</bean>
<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg index="0" ref="jedisPoolConfig"/>
<constructor-arg index="1" value="${redis.host}"/>
<constructor-arg index="2" value="${redis.port}" type="int"/>
<constructor-arg index="3" value="${redis.timeout}" type="int"/>
<constructor-arg index="4" value="${redis.pass}"/>
</bean>
<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1">
<list>
<ref bean="jedis.shardInfo1" />
</list>
</constructor-arg>
</bean>
</beans>
大家可以看见,我这个配置文件写的比较奇葩...
因为我一共写了两个pool的bean,由于目前项目redis还是单机版本,所以我只是使用JedisPool这个进行之后的操作。ShardedJedisPool这个适用于分布式redis缓存的连接,但是我有一天突然发现没有flushDB的方法,我一着急,就换做了JedisPool,以后加强学习,把更加适用的方法总结出来。
RedisDataSource
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
@Repository("jedisDS")
public class JedisDataSourceImpl implements JedisDataSource{
private static final Logger LOGGER = LoggerFactory.getLogger(JedisDataSourceImpl.class);
@Autowired
private ShardedJedisPool shardedJedisPool;
@Autowired
private JedisPool jedisPool;
@Override
public ShardedJedis getShardedRedisClient() {
ShardedJedis shardedJedis = null;
try{
shardedJedis = shardedJedisPool.getResource();
//shardedJedisPool.
return shardedJedis;
}catch (Exception e){
LOGGER.error("[JedisDS] getRedisClient error: "+e.getMessage());
if(null!=shardedJedis){
shardedJedis.close();
}
return null;
}
}
@Override
public Jedis getRedisClient() {
Jedis jedis = null;
try{
jedis = jedisPool.getResource();
return jedis;
}catch (Exception e){
if(null!=jedis){
jedis.close();
}
LOGGER.error("[JedisDS] getJedisClient error: "+e.getMessage());
}
return null;
}
@Override
public void returnResource(ShardedJedis shardedJedis) {
shardedJedis.close();
}
@Override
public void returnResource(ShardedJedis shardedJedis, boolean broken) {
shardedJedis.close();
}
@Override
public void returnResource(Jedis jedis, boolean broken) {
jedis.close();
}
}
上面的代码写了两种JedisPool和ShardedJedisPool两种方式
RedisCilentTamplate
这里整理了一些简单的方法,可以直接调用,可以直接参考一下
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.ShardedJedis;
@Repository("redisClientTemplate")
public class RedisClientTemplate {
private static final Logger log = LoggerFactory.getLogger(RedisClientTemplate.class);
@Autowired
private JedisDataSource redisDataSource;
public void disconnect() {
ShardedJedis shardedJedis = redisDataSource.getShardedRedisClient();
shardedJedis.disconnect();
}
/**
* 设置单个值
*
* @param key
* @param value
* @return
*/
public String set(String key, String value) {
String result = null;
ShardedJedis shardedJedis = redisDataSource.getShardedRedisClient();
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.set(key, value);
} catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
}
/**
* 获取单个值
*
* @param key
* @return
*/
public String get(String key) {
String result = null;
ShardedJedis shardedJedis = redisDataSource.getShardedRedisClient();
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.get(key);
} catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
}
public Boolean exists(String key) {
Boolean result = false;
ShardedJedis shardedJedis = redisDataSource.getShardedRedisClient();
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.exists(key);
} catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
}
public String type(String key) {
String result = null;
ShardedJedis shardedJedis = redisDataSource.getShardedRedisClient();
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.type(key);
} catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
}
/**
* 在某段时间后失效
*
* @param key
* @param seconds
* @return
*/
public Long expire(String key, int seconds) {
Long result = null;
ShardedJedis shardedJedis = redisDataSource.getShardedRedisClient();
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.expire(key, seconds);
} catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
}
/**
* 在某个时间点失效
*
* @param key
* @param unixTime
* @return
*/
public Long expireAt(String key, long unixTime) {
Long result = null;
ShardedJedis shardedJedis = redisDataSource.getShardedRedisClient();
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.expireAt(key, unixTime);
} catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
}
public Long ttl(String key) {
Long result = null;
ShardedJedis shardedJedis = redisDataSource.getShardedRedisClient();
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.ttl(key);
} catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
}
public boolean setbit(String key, long offset, boolean value) {
ShardedJedis shardedJedis = redisDataSource.getShardedRedisClient();
boolean result = false;
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.setbit(key, offset, value);
} catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
}
public boolean getbit(String key, long offset) {
ShardedJedis shardedJedis = redisDataSource.getShardedRedisClient();
boolean result = false;
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.getbit(key, offset);
} catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
}
public long setRange(String key, long offset, String value) {
ShardedJedis shardedJedis = redisDataSource.getShardedRedisClient();
long result = 0;
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.setrange(key, offset, value);
} catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
}
public String getRange(String key, long startOffset, long endOffset) {
ShardedJedis shardedJedis = redisDataSource.getShardedRedisClient();
String result = null;
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.getrange(key, startOffset, endOffset);
} catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
}
public boolean del(String key){
ShardedJedis shardedJedis = redisDataSource.getShardedRedisClient();
boolean temp = false;
if (shardedJedis == null) {
return false;
}
boolean broken = false;
try {
shardedJedis.del(key);
temp = true;
} catch (Exception e) {
log.error(e.getMessage(), e);
temp = false;
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
return temp;
}
}
public boolean fushAll(){
boolean temp = false;
Jedis jedis = redisDataSource.getRedisClient();
boolean broken = false;
try{
jedis.flushDB();
return true;
}catch (Exception e){
log.error(e.getMessage(), e);
temp = false;
broken = true;
}finally {
redisDataSource.returnResource(jedis, broken);
return temp;
}
}
}
Redis和Spring整合的更多相关文章
- redis与spring整合实例
1)首先是redis的配置. 使用的是maven工程,引入redis与spring整合的相关jar包 <!-- redis服务 start--> <dependency> &l ...
- 分布式缓存技术redis学习系列(五)——redis实战(redis与spring整合,分布式锁实现)
本文是redis学习系列的第五篇,点击下面链接可回看系列文章 <redis简介以及linux上的安装> <详细讲解redis数据结构(内存模型)以及常用命令> <redi ...
- 分布式缓存技术redis系列(五)——redis实战(redis与spring整合,分布式锁实现)
本文是redis学习系列的第五篇,点击下面链接可回看系列文章 <redis简介以及linux上的安装> <详细讲解redis数据结构(内存模型)以及常用命令> <redi ...
- redis系列之5----redis实战(redis与spring整合,分布式锁实现)
本文是redis学习系列的第五篇,点击下面链接可回看系列文章 <redis简介以及linux上的安装> <详细讲解redis数据结构(内存模型)以及常用命令> <redi ...
- Redis跟Spring整合,sentinel模式
普通模式整合 一.在pom.xml中引入redis的依赖 <dependency> <groupId>org.springframework.data</groupId& ...
- redis 与 spring整合 hash 增删改操作 list增删改操作
本人,对于以前redis的学习是非常痛苦的!近期将以前的东西捡起来.以博客的形式存储,以便于以后快速捡起来,并和广大同胞一起分享! 1):简单介绍 redis 是基于C语言开发. redis是一个ke ...
- Redis + Jedis + Spring整合遇到的异常(转)
项目中需要用到缓存,经过比较后,选择了redis,客户端使用jedis连接,也使用到了spring提供的spring-data-redis.配置正确后启动tomcat,发现如下异常: Caused b ...
- redis和spring整合使用
第一步,在项目中加入redis的pom代码: <dependency> <groupId>redis.clients</groupId> <artifactI ...
- redis与spring整合·
单机版: 配置spring配置文件applicationContext.xml <?xml version="1.0" encoding="UTF-8"? ...
随机推荐
- 消除input,button之间的间距
代码: 效果: 问题: input,button标签之间出现了间距,这并不是我们所期望的. 解决方法: 1.在父级元素上设置属性:font-size:0px; 将input父级字体(font-size ...
- CSS实现覆盖弹窗(效果如JQuery-UI的Dialog)
原理:定义一个新的div用来覆盖整个页面,再把想要弹出的窗口放在这个div上面 1.定义一个div,设置其隐藏(display:none),用于覆盖整个页面,并设置其CSS属性为: #divBg { ...
- TypeScript设计模式之门面、适配器
看看用TypeScript怎样实现常见的设计模式,顺便复习一下. 学模式最重要的不是记UML,而是知道什么模式可以解决什么样的问题,在做项目时碰到问题可以想到用哪个模式可以解决,UML忘了可以查,思想 ...
- [LeetCode]House Robber II (二次dp)
213. House Robber II Total Accepted: 24216 Total Submissions: 80632 Difficulty: Medium Note: Thi ...
- 每天一个Linux命令 2
wc 命令用于统计指定文本的行数.字数.字节数.格式为“wc [参数] 文本” . 参数 作 ...
- UIImagePickerController拍照/相册/录像/本地视频
1.导入系统库 #import <MobileCoreServices/MobileCoreServices.h> 2.遵守协议 <UIImagePickerControllerDe ...
- java深拷贝和浅拷贝
1.概念 java里的clone分为: A:浅复制(浅克隆): 浅复制仅仅复制所考虑的对象,而不复制它所引用的对象. b:深复制(深克隆):深复制把要复制的对象所引用的对象都复制了一遍. Java中对 ...
- 多线程爬坑之路-ThreadLocal源码及原理的深入分析
ThreadLocal<T>类:以空间换时间提供一种多线程更快捷访问变量的方式.这种方式不存在竞争,所以也不存在并发的安全性问题. This class provides thread-l ...
- Solr DateRangeField
Solr DateRangeField 是solr5.0 实现的一个feature. 关于 DateRangeField 支持日期查询如 date_field:[2016-03-23 TO 2017 ...
- mybatis源码跟踪
第一步:从web.xml进入dispatcherServlet进入前端控制器 第二步:使用handlerMapping 获得handlerChain 第三步:使用适配器执行handler获取model ...