欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

redis 与 Spring 集成 redisspring 

程序员文章站 2022-07-12 17:21:14
...
ApplicationContent-reids.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

<context:property-placeholder location="classpath:redis.properties" />
<context:component-scan base-package="com.sc.ew.redis" />

<bean id="shardedJedisPools" class="redis.clients.jedis.ShardedJedisPool">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1">
<list>
<!-- <bean name="slaver" class="redis.clients.jedis.JedisShardInfo">
<constructor-arg index="0" value="${redis.slaver.host}" />
<constructor-arg index="1" value="${redis.slaver.port}" type="int" />
</bean> -->
<bean name="master" class="redis.clients.jedis.JedisShardInfo">
<constructor-arg index="0" value="192.168.1.250" />
<constructor-arg index="1" value="6379" type="int" />
<constructor-arg index="2" value="10000" type="int" />
</bean>
</list>
</constructor-arg>
</bean>

<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="5000" />
<property name="maxIdle" value="1000" />
<property name="minIdle" value="50" />
<property name="numTestsPerEvictionRun" value="1024" />
<property name="timeBetweenEvictionRunsMillis" value="30000" />
<property name="minEvictableIdleTimeMillis" value="-1" />
<property name="softMinEvictableIdleTimeMillis" value="10000" />
<property name="maxWaitMillis" value="10000" />
<property name="testOnBorrow" value="true" />
<property name="testWhileIdle" value="true" />
<property name="testOnReturn" value="false" />
<property name="jmxEnabled" value="true" />
<property name="jmxNamePrefix" value="youyuan" />
<property name="blockWhenExhausted" value="false" />
</bean>
</beans>




package com.sc.ew.redis.dao.source;

import redis.clients.jedis.ShardedJedis;

public interface RedisDataSource {
/**
* 取得redis的客户端,可以执行命令了。
* @return
*/
public abstract ShardedJedis getRedisClient();

public void returnResource(ShardedJedis shardedJedis);// 将资源返还给pool

public void returnResource(ShardedJedis shardedJedis, boolean broken);// 出现异常后,将资源返还给pool (其实不需要第二个方法)
}





package com.sc.ew.redis.dao.source.impl;

import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import com.sc.ew.redis.dao.source.RedisDataSource;

@Repository
public class RedisDataSourceImpl implements RedisDataSource {

private static final Logger logger = Logger
.getLogger(RedisDataSourceImpl.class);

@Resource
private ShardedJedisPool shardedJedisPool;

public ShardedJedis getRedisClient() {
try {
ShardedJedis shardJedis = shardedJedisPool.getResource();
return shardJedis;
} catch (Exception e) {
logger.error("getRedisClent error", e);
}
return null;
}

public void returnResource(ShardedJedis shardedJedis) {
shardedJedisPool.returnResource(shardedJedis);
}

public void returnResource(ShardedJedis shardedJedis, boolean broken) {
if (broken) {
shardedJedisPool.returnBrokenResource(shardedJedis);
} else {
shardedJedisPool.returnResource(shardedJedis);
}
}
}




package com.sc.ew.redis.template;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.sc.ew.redis.dao.source.RedisDataSource;
import com.sc.ew.redis.util.SerializationUtils;
import redis.clients.jedis.ShardedJedis;

@Repository
public class RedisHashTemplate {

private static final Logger logger = Logger
.getLogger(RedisHashTemplate.class);

@Autowired
private RedisDataSource redisDataSource;

public void disconnect() {
ShardedJedis shardedJedis = redisDataSource.getRedisClient();
shardedJedis.disconnect();
}

/**
* 将哈希表 key 中的域 field 的值设为 value 。 如果 key 不存在,一个新的哈希表被创建并进行 HSET 操作。 如果域
* field 已经存在于哈希表中,旧值将被覆盖。
*
* @param key
* @param field
* @param value
* @return
*/
public Long hset(String key, String field, String value) {
Long result = null;
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
result = shardedJedis.hset(key, field, value);
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return result;
}

/**
* 将哈希表 key 中的域 field 的值设为 value 。 如果 key 不存在,一个新的哈希表被创建并进行 HSET 操作。 如果域
* field 已经存在于哈希表中,旧值将被覆盖。
*
* @param key
* @param field
* @param value
* @return
*/
public Long hsetObject(String key, String field, Object object) {
Long result = null;
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
result = shardedJedis.hset(key.getBytes(), field.getBytes(),
SerializationUtils.serialize(object));
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return result;
}

/**
* 返回哈希表 key 中给定域 field 的值。
*
* @param key
* @param field
* @return
*/
public String hget(String key, String field) {
String result = null;
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
result = shardedJedis.hget(key, field);
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return result;
}

/**
* 返回哈希表 key 中给定域 field 的值。
*
* @param key
* @param field
* @return
*/
public Object hgetObject(String key, String field) {
Object result = null;
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
result = SerializationUtils.deserialize(shardedJedis.hget(
key.getBytes(), field.getBytes()));
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return result;
}

/**
* 将哈希表 key 中的域 field 的值设置为 value ,当且仅当域 field 不存在。 若域 field 已经存在,该操作无效。 如果
* key 不存在,一个新哈希表被创建并执行 HSETNX 命令。
*
* @param key
* @param field
* @param value
* @return
*/
public Long hsetnx(String key, String field, String value) {
Long result = null;
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
result = shardedJedis.hsetnx(key, field, value);
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return result;
}

/**
* 同时将多个 field-value (域-值)对设置到哈希表 key 中。 此命令会覆盖哈希表中已存在的域。
*
* @param key
* @param hash
* @return
*/
public String hmset(String key, Map<String, String> hash) {
String result = null;
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
result = shardedJedis.hmset(key, hash);
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return result;
}

/**
* 同时将多个 field-value (域-值)对设置到哈希表 key 中。 此命令会覆盖哈希表中已存在的域。
*
* @param key
* @param hash
* @return
*/
public String hmsetObject(String key, Map<String, Object> hashs) {
String result = null;
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
Map<byte[], byte[]> byteHash = new HashMap<byte[], byte[]>();
for (Map.Entry<String, Object> setMap : hashs.entrySet()) {
String keyMap = setMap.getKey();
Object valMap = setMap.getValue();
byteHash.put(keyMap.getBytes(),
SerializationUtils.serialize(valMap));
}

result = shardedJedis.hmset(key.getBytes(), byteHash);
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return result;
}

/**
* 同时将多个 field-value (域-值)对设置到哈希表 key 中。 此命令会覆盖哈希表中已存在的域。
*
* @param key
* @param hash
* @return
*/
public String hmsetMapObject(String key, Map<String, Map<String, Object>> hashs) {
String result = null;
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
Map<byte[], byte[]> byteHash = new HashMap<byte[], byte[]>();
for (Map.Entry<String, Map<String, Object>> setMap : hashs.entrySet()) {
String keyMap = setMap.getKey();
Object valMap = setMap.getValue();
byteHash.put(keyMap.getBytes(),
SerializationUtils.serialize(valMap));
}

result = shardedJedis.hmset(key.getBytes(), byteHash);
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return result;
}

/**
* 返回哈希表 key 中,一个或多个给定域的值。 如果给定的域不存在于哈希表,那么返回一个 nil 值。
*
* @param key
* @param fields
* @return
*/
public List<String> hmget(String key, String... fields) {
List<String> result = null;
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
result = shardedJedis.hmget(key, fields);
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return result;
}

/**
* 返回哈希表 key 中,一个或多个给定域的值。 如果给定的域不存在于哈希表,那么返回一个 nil 值。
*
* @param key
* @param fields
* @return
*/
public List<Object> hmgetObject(String key, String... fields) {
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
byte[][] bytes = new byte[fields.length][];
for (int i = 0; i < fields.length; i++) {
bytes[i] = fields[i].getBytes();
}
List<byte[]> resultList = shardedJedis.hmget(key.getBytes(), bytes);
List<Object> resultObject = new ArrayList<Object>();
for (byte[] byteList : resultList) {
resultObject.add(SerializationUtils.deserialize(byteList));
}
return resultObject;
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return null;
}

/**
* 为哈希表 key 中的域 field 的值加上增量 increment 。 增量也可以为负数,相当于对给定域进行减法操作。
*
* @param key
* @param field
* @param value
* @return
*/
public Long hincrBy(String key, String field, long value) {
Long result = null;
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
result = shardedJedis.hincrBy(key, field, value);

} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return result;
}

/**
* 查看哈希表 key 中,给定域 field 是否存在。
*
* @param key
* @param field
* @return
*/
public Boolean hexists(String key, String field) {
Boolean result = false;
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
result = shardedJedis.hexists(key, field);
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return result;
}

/**
* 删除哈希表 key 中的一个或多个指定域,不存在的域将被忽略。
*
* @param key
* @param field
* @return
*/
public Long hdelAll(String key) {
Long result = null;
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
Set<String> keys = hkeys(key);
if(keys.size() > 0){
String[] arr = new String[keys.size()];
keys.toArray(arr);
result = hdel(key, arr);
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return result;
}

/**
* 删除哈希表 key 中的一个或多个指定域,不存在的域将被忽略。
*
* @param key
* @param field
* @return
*/
public Long hdel(String key, String... field) {
Long result = null;
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
result = shardedJedis.hdel(key, field);
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return result;
}

/**
* 返回哈希表 key 中域的数量。
*
* @param key
* @return
*/
public Long hlen(String key) {
Long result = null;
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
result = shardedJedis.hlen(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return result;
}

/**
* 返回哈希表 key 中的所有域。
*
* @param key
* @return
*/
public Set<String> hkeys(String key) {
Set<String> result = null;
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
result = shardedJedis.hkeys(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return result;
}

/**
* 返回哈希表 key 中所有域的值。
*
* @param key
* @return
*/
public List<String> hvals(String key) {
List<String> result = null;
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
result = shardedJedis.hvals(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return result;
}

/**
* 返回哈希表 key 中,所有的域和值。 在返回值里,紧跟每个域名(field
* name)之后是域的值(value),所以返回值的长度是哈希表大小的两倍。
*
* @param key
* @return
*/
public Map<String, String> hgetAll(String key) {
Map<String, String> result = null;
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
result = shardedJedis.hgetAll(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return result;
}

/**
* 返回哈希表 key 中,所有的域和值。 在返回值里,紧跟每个域名(field
* name)之后是域的值(value),所以返回值的长度是哈希表大小的两倍。
*
* @param key
* @return
*/
public Map<String, Object> hgetAllObject(String key) {
Map<String, Object> result = null;
ShardedJedis shardedJedis = null;
boolean broken = false;
try {
shardedJedis = redisDataSource.getRedisClient();
Map<byte[], byte[]> resultByteMap = shardedJedis.hgetAll(key
.getBytes());
result = new HashMap<String, Object>();
for (Map.Entry<byte[], byte[]> entrySet : resultByteMap.entrySet()) {
byte[] keyMap = entrySet.getKey();
byte[] valMap = entrySet.getValue();
result.put(new String(keyMap),
SerializationUtils.deserialize(valMap));
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
}finally {
            redisDataSource.returnResource(shardedJedis, broken);
        }
return result;
}
}
相关标签: redis spring