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;
}
}
}