spring-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">
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="30" />
<property name="maxIdle" value="60000" />
<property name="maxWaitMillis" value="30000" />
<property name="testOnBorrow" value="true" />
</bean>
<!--redis哨兵模式配置-->
<bean id="redisSentinelConfiguration" class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
<!-- 配置master主服务器的名称 -->
<property name="master">
<bean class="org.springframework.data.redis.connection.RedisNode">
<property name="name" value="#{coreDao['redis.sentinel.master.name']}"></property>
</bean>
</property>
<!--配置哨兵信息-->
<property name="sentinels">
<set>
<bean class="org.springframework.data.redis.connection.RedisNode">
<constructor-arg name="host" value="#{coreDao['redis.sentinel.host1']}"></constructor-arg>
<constructor-arg name="port" value="#{coreDao['redis.sentinel.port1']}"></constructor-arg>
</bean>
<bean class="org.springframework.data.redis.connection.RedisNode">
<constructor-arg name="host" value="#{coreDao['redis.sentinel.host2']}"></constructor-arg>
<constructor-arg name="port" value="#{coreDao['redis.sentinel.port2']}"></constructor-arg>
</bean>
<bean class="org.springframework.data.redis.connection.RedisNode">
<constructor-arg name="host" value="#{coreDao['redis.sentinel.host3']}"></constructor-arg>
<constructor-arg name="port" value="#{coreDao['redis.sentinel.port3']}"></constructor-arg>
</bean>
</set>
</property>
</bean>
<!--redis哨兵模式配置-->
<bean id="redisSentinelConfiguration" class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
<!-- 配置master主服务器的名称 -->
<property name="master">
<bean class="org.springframework.data.redis.connection.RedisNode">
<property name="name" value="#{coreDao['redis.sentinel.master.name']}"></property>
</bean>
</property>
<!--配置哨兵信息-->
<property name="sentinels">
<set>
<bean class="org.springframework.data.redis.connection.RedisNode">
<constructor-arg name="host" value="#{coreDao['redis.sentinel.host1']}"></constructor-arg>
<constructor-arg name="port" value="#{coreDao['redis.sentinel.port1']}"></constructor-arg>
</bean>
<bean class="org.springframework.data.redis.connection.RedisNode">
<constructor-arg name="host" value="#{coreDao['redis.sentinel.host2']}"></constructor-arg>
<constructor-arg name="port" value="#{coreDao['redis.sentinel.port2']}"></constructor-arg>
</bean>
<bean class="org.springframework.data.redis.connection.RedisNode">
<constructor-arg name="host" value="#{coreDao['redis.sentinel.host3']}"></constructor-arg>
<constructor-arg name="port" value="#{coreDao['redis.sentinel.port3']}"></constructor-arg>
</bean>
</set>
</property>
</bean>
<bean id="redisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<constructor-arg name="poolConfig" ref="jedisPoolConfig" />
<constructor-arg name="sentinelConfig" ref="redisSentinelConfiguration" />
<property name="database" value="#{coreDao['redis.database']}"/>
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="redisConnectionFactory" />
</bean>
</beans>
#Redis哨兵模式
redis.sentinel.master.name=sentinel-172.16.111.111-6379
redis.sentinel.host1=172.16.111.111
redis.sentinel.port1=6379
redis.pass=
redis.sentinel.host2=172.16.111.112
redis.sentinel.port2=6380
redis.sentinel.host3=172.16.111.113
redis.sentinel.port3=6380
redis.database=12
---java代码
调用Redis时,注入RedisCommonService 直接调用get和set获取redis数据
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.SortParameters.Order;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.query.SortQueryBuilder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* redis公用类
*/
@Service
public class RedisCommonService {
/**
* 注入template
*/
@Resource
@Qualifier("redisTemplate")
protected RedisTemplate<String, String> template;
/**
* 保存key-value 类型数据
*
* @param key
*/
public Set<String> getKeys(String key) {
return template.keys(key);
}
/**
* 保存key-value 类型数据
*
* @param key
* @param value
*/
public void saveKeyAndValue(String key, String value) {
template.opsForValue().set(key, value);
}
/**
* 保存key-value 类型数据
*
* @param namespace
* @param key
* @param value
*/
public void set(String namespace, String key, String value) {
this.saveKeyAndValue(namespace + ":" + key, value);
}
/**
* 获取key-value 类型数据
*
* @param namespace
* @param key
* @return
*/
public String get(String namespace, String key) {
return this.findKeyAndValue(namespace + ":" + key);
}
/**
* 设置key-value 数据并设置超时时间
*
* @param key
* @param value
* @param timeOut 超时时间
* @param timeUtit 时间单位
* @return
*/
public boolean saveKeyTimeOut(String key, String value, long timeOut, TimeUnit timeUtit) {
template.opsForValue().set(key, value);
return this.setKeyExpire(key, timeOut, timeUtit);
}
/**
* 保存或修改hash值到对象
*
* @param key
* @param hashKey
* @param value
*/
public void saveHashToObj(String key, String hashKey, String value) {
template.opsForHash().put(key, hashKey, value);
}
/**
* 保存或修改set值到对象
*
* @param key
* @param value
*/
public long saveSetValue(String key, String value) {
return template.opsForSet().add(key, value);
}
/**
* @param key
* @return boolean
* @Title exists
* @Description 判断key是否存在
*/
public boolean exists(String key) {
return ((Boolean) template.execute(new RedisCallback<Object>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
byte[] bytes = new byte[key.length() + 1];
try {
bytes = key.getBytes("UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return connection.exists(bytes);
}
})).booleanValue();
}
/**
* 获取key-value 类型数据
*
* @param key
*/
public String findKeyAndValue(String key) {
return template.opsForValue().get(key);
}
/**
* 设置key过期时间
*
* @param key
* @param timeout
* @param timeUtit
* @return
*/
public boolean setKeyExpire(String key, long timeout, TimeUnit timeUtit) {
return template.expire(key, timeout, timeUtit);
}
/**
* 根据key获取对象
*
* @param key 要查找的对象的key
* @return 单个对象信息
*/
public Map<Object, Object> findObj(String key) {
return template.opsForHash().entries(key);
}
public <T> T findObj(String key, Class<T> target, ObjectMapper mapper) throws JsonParseException, JsonMappingException, IOException {
Map<Object, Object> entries = template.opsForHash().entries(key);
if (null == entries || entries.size() == 0) {
return null;
}
String jsonStr = JSON.toJSONString(entries);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return null == jsonStr || "{}".equals(jsonStr) ? null : mapper.readValue(jsonStr, target);
}
/**
* 跟据key和列名获取值
*
* @param key 对象key
* @param hashKey 列名
* @return 对象hash的value值
*/
public Object findValByObj(String key, String hashKey) {
return template.opsForHash().get(key, hashKey);
}
/**
* 获取列表(例如:商品和项目 ,key= project:goods:11, keyPattern= goods:, sortHash= goodsPrice,hashType=true)
*
* @param key 列表key
* @param keyPattern 匹配项
* @param sortHash 要排序的自动
* @param isDesc 是否为降序
* @param hashType 是否为字符串
* @return 数据列表
*/
public List<Map<Object, Object>> getSortList(String key, String keyPattern, String sortHash, boolean isDesc, boolean hashType) {
SortQueryBuilder<String> builder = SortQueryBuilder.sort(key);
builder.by(keyPattern + "*->" + sortHash);
builder.get("#"); //后续可以配置为多个,直接查询并返回值
builder.alphabetical(hashType);
if (isDesc) {
builder.order(Order.DESC);
}
List<String> childKeys = template.sort(builder.build());
List<Map<Object, Object>> result = new ArrayList<Map<Object, Object>>();
for (String ckey : childKeys) {
result.add(template.opsForHash().entries(keyPattern + ckey));
}
return result;
}
/**
* 获取列表(例如:商品和项目 ,key= project:goods:11, keyPattern= goods:, sortHash= goodsPrice,hashType=true)
*
* @param key 列表key
* @param keyPattern 匹配项
* @param sortHash 要排序的自动
* @param isDesc 是否为降序
* @param hashType 是否为字符串
* @param target class类型
* @param mapper ObjectMapper
* @return 数据列表
* @throws Exception
* @throws JsonMappingException
* @throws JsonParseException
*/
public <T> List<T> getSortList(String key, String keyPattern, String sortHash, boolean isDesc, boolean hashType, Class<T> target, ObjectMapper mapper) throws JsonParseException, JsonMappingException, Exception {
SortQueryBuilder<String> builder = SortQueryBuilder.sort(key);
builder.by(keyPattern + "*->" + sortHash);
builder.get("#"); //后续可以配置为多个,直接查询并返回值
builder.alphabetical(hashType);
if (isDesc) {
builder.order(Order.DESC);
}
List<String> childKeys = template.sort(builder.build());
List<T> result = new ArrayList<T>();
for (String ckey : childKeys) {
result.add(findObj(keyPattern + ckey, target, mapper));
}
return result;
}
/**
* 获取列表(例如:商品和项目 ,key= project:goods:11, keyPattern= goods:, sortHash= goodsPrice,hashType=true)
*
* @param key 列表key
* @param keyPattern 匹配项
* @param target class类型
* @param mapper ObjectMapper
* @return 数据列表
* @throws Exception
* @throws JsonMappingException
* @throws JsonParseException
*/
public <T> List<T> getList(String key, String keyPattern, int offset, int count, Class<T> target, ObjectMapper mapper) throws JsonParseException, JsonMappingException, Exception {
/*SortQueryBuilder<String> builder = SortQueryBuilder.sort(key);
builder.get("#");
builder.limit(offset, count);*/
List<String> childKeys = template.opsForList().range(key, offset, count);
List<T> result = new ArrayList<T>();
for (String ckey : childKeys) {
result.add(findObj(keyPattern + ckey, target, mapper));
}
return result;
}
/**
* 获取部分列表(例如:商品和项目 ,key= project:goods:11, keyPattern= goods:, sortHash= goodsPrice)
*
* @param key 列表key
* @param keyPattern 匹配项
* @param sortHash 要排序的自动
* @param isDesc 是否为降序
* @param hashType 是否为字符串
* @param offset 开始下标
* @param count 条数
* @return 匹配key列表
*/
public List<String> getSortPageList(String key, String keyPattern, String sortHash, boolean isDesc, boolean hashType, int offset, int count) {
SortQueryBuilder<String> builder = SortQueryBuilder.sort(key);
builder.by(keyPattern + "*->" + sortHash);
builder.get("#"); //后续可以配置为多个,直接查询并返回值
builder.alphabetical(hashType);
if (isDesc) {
builder.order(Order.DESC);
}
builder.limit(offset, count);
List<String> childKeys = template.sort(builder.build());
return childKeys;
}
/**
* 获取部分列表(例如:商品和项目 ,key= project:goods:11, keyPattern= goods:, sortHash= goodsPrice)
*
* @param key 列表key
* @param keyPattern 匹配项
* @param sortHash 要排序的字段
* @param isDesc 是否为降序
* @param hashType 是否为字符串
* @param offset 开始下标
* @param count 条数
* @param target class类型
* @param mapper ObjectMapper
* @return 数据列表
* @throws Exception
* @throws JsonMappingException
* @throws JsonParseException
*/
public <T> List<T> getSortPageList(String key, String keyPattern, String sortHash, boolean isDesc, boolean hashType, int offset, int count, Class<T> target, ObjectMapper mapper) throws JsonParseException, JsonMappingException, Exception {
SortQueryBuilder<String> builder = SortQueryBuilder.sort(key);
builder.by(keyPattern + "*->" + sortHash);
builder.get("#"); //后续可以配置为多个,直接查询并返回值
builder.alphabetical(hashType);
if (isDesc) {
builder.order(Order.DESC);
}
builder.limit(offset, count);
List<String> childKeys = template.sort(builder.build());
List<T> result = new ArrayList<T>();
for (String ckey : childKeys) {
result.add(findObj(keyPattern + ckey, target, mapper));
}
return result;
}
/**
* 向list中追加值
*
* @param key
* @param value
*/
public void saveValueToList(String key, String value) {
template.opsForList().remove(key, 1, value);
template.opsForList().leftPush(key, value);
}
/**
* 从list中删除值
*
* @param key
* @param value
*/
public void deleteValueFromList(String key, String value) {
template.opsForList().remove(key, 1, value);
}
/**
* 删除key
*
* @param key
*/
public void deleteObj(String key) {
template.delete(key);
}
/**
* 获得list个数
*
* @param key
* @return
*/
public Long getListSize(String key) {
return template.opsForList().size(key);
}
/**
* 增加hash存贮某一字段的值
*
* @param key
* @param field
* @param count
*/
public long increaseHashValue(String key, String field, Long count) {
return template.opsForHash().increment(key, field, count);
}
/**
* 专题产品募集者总金额
*
* @param key
* @param score
*/
public void increaseZsetScore(String name, String key, double score) {
template.opsForZSet().incrementScore(name, key, score);
}
/**
* 获取权重
*
* @param key
* @param value
* @return
*/
public Double getZsetScore(String key, String value) {
return template.opsForZSet().score(key, value);
}
public List<String> getWithHlodingList(String key) {
Long end = template.opsForList().size(key);
List<String> lst = template.opsForList().range(key, 0, end);
return lst;
}
}