您的位置:首页 > 数据库 > Redis

简单示例:Spring4 整合 单个Redis服务

2017-10-15 10:45 627 查看
1. 引入spring-data-redis.jar

  API:https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/core/package-summary.html#package.description

2. spring配置文件添加如下配置

<!-- redis配置 -->
<context:property-placeholder location="classpath:redis.properties" />
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxTotal" value="${redis.maxTotal}" />
<!--<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />-->
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
<!--<property name="testOnReturn" value="${redis.testOnReturn}" />-->
<!--<property name="blockWhenExhausted" value="${redis.blockWhenExhausted}" />-->
</bean>

<!--<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"-->
<!--p:hostName="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:poolConfig-ref="poolConfig"/>-->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:hostName="${redis.host}" p:port="${redis.port}" p:poolConfig-ref="poolConfig"/>

<!-- SDR默认采用的序列化策略有两种,一种是String的序列化策略,一种是JDK的序列化策略。 StringRedisTemplate默认采用的是String的序列化策略,保存的key和value都是采
用此策略序列化保存的。 RedisTemplate默认采用的是JDK的序列化策略,保存的key和value都是采用此策略序列化保存的。 就是因为序列化策略的不同,即使是同一个key用不同的
Template去序列化,结果是不同的。所以根据key去删除数据的时候就出现了删除失败的问题。 --> <!-- redis 序列化策略 ,通常情况下key值采用String序列化策略, -->

<!-- 如果不指定序列化策略,StringRedisTemplate的key和value都将采用String序列化策略; -->
<!-- 但是RedisTemplate的key和value都将采用JDK序列化 这样就会出现采用不同template保存的数据不能用同一个template删除的问题 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory"   ref="connectionFactory" />
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
<property name="enableTransactionSupport" value="true" />
</bean>


# Redis settings

#redis的服务器地址
redis.host=localhost
#redis的服务端口
redis.port=6379
#密码
redis.pass=123

#最大空闲数
redis.maxIdle=300
#最大总数
redis.maxTotal=1000
#指明是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
redis.testOnBorrow=true


3. Redis工具类

package com.*;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
* Created by Administrator on 2017/3/8.
*/
@Component
public class RedisManager<T> {
private Logger log = Logger.getLogger(RedisManager.class);

@Autowired
private RedisTemplate redisTemplate;

/** =================================== Hash ====================================================**/

/**
* 缓存Map
*
* @param key
* @param hashKey
* @param t
* @return
*/
public void setCacheMap(String key, String hashKey, T t) {
BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(key);
boundHashOperations.put(hashKey, t);
//        boundHashOperations.expire(BasConstant.MEMORY_TOKEN_EXPIRES, TimeUnit.DAYS);
//        redisTemplate.opsForValue().set(realToken, studentVo, BasConstant.TOKEN_EXPIRES_HOUR, TimeUnit.DAYS);
//存储到redis并设置过期时间
//        redisTemplate.boundValueOps(realToken).set(studentVo, BasConstant.TOKEN_EXPIRES_HOUR, TimeUnit.DAYS);
}

/**
* 获得缓存的Map
*
* @param key //* @param hashOperation
* @return
*/
public <T> Map<String, T> getCacheMap(String key/*,HashOperations<String,String,T> hashOperation*/) {
Map<String, T> map = redisTemplate.opsForHash().entries(key);
/*Map<String, T> map = hashOperation.entries(key);*/
return map;
}

/**
* 获取缓存的map大小
*
* @param key
* @return
*/
public long getCacheMapSize(String key) {
return redisTemplate.opsForHash().size(key);
}

/**
* 获取map的value值
*
* @param key     key
* @param hashKey field
* @return
*/
public Object getMapValue(String key, String hashKey) {
return redisTemplate.opsForHash().get(key, hashKey);
}

/**
* 是否存在 key 及 field
*
* @param key     key
* @param hashKey field
* @return
*/
public boolean hasHashKey(String key, String hashKey) {
return redisTemplate.opsForHash().hasKey(key, hashKey);
}

/**
* 延期
*
* @param key
* @return
*/
public boolean expireHash(String key, long time) {
return redisTemplate.boundHashOps(key).expire(time, TimeUnit.DAYS);
}

/**
* 从redis中删除key缓存
*
* @param key
*/
public void deleteHashKey(String key, Object... hashKeys) {
redisTemplate.opsForHash().delete(key, hashKeys);
}

/** =================================== 通用 ====================================================**/

/**
* 从redis中删除key缓存
*
* @param key
*/
public void deleteKey(String key, Object... hashKeys) {
redisTemplate.delete(key);
}

/**
* 是否存在key
*
* @param key
* @return 是否存在key
*/
public boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}

/**
* 延期
*
* @param key 键值
* @return
*/
public boolean expire(String key, long time, TimeUnit timeUnit) {
return redisTemplate.expire(key, time, timeUnit);
}

/** =================================== List ====================================================**/

/**
* list缓存
*
* @param key
* @param value
* @return
*/
public boolean setCacheList(String key, String value) {
try {
ListOperations<String, String> listOps = redisTemplate.opsForList();
listOps.rightPush(key, value);
return true;
} catch (Throwable t) {
log.error("缓存[" + key + "]失败, value[" + value + "]", t);
}
return false;
}

public void setValueForList(String key, long index, Object value){
BoundListOperations listOps = redisTemplate.boundListOps(key);
listOps.set(index, value);
}

/**
* 缓存list
*
* @param key  键值
* @param list value
* @return
*/
public void setCacheList(String key, List list) {
BoundListOperations listOps = redisTemplate.boundListOps(key);
//只能以数组形式存放
listOps.rightPushAll(list.toArray());
}

/**
* 获取list缓存 - 根据起始~终止位置
*
* @param key   键值
* @param start 起始位置
* @param end   截止位置
* @return
*/
public List getList(String key, long start, long end) {
List list = null;
try {
BoundListOperations listOperations = redisTemplate.boundListOps(key);
list = listOperations.range(start, end);
} catch (Throwable t) {
log.error("获取list缓存失败key[" + key + ", error[" + t + "]");
}
return list;
}

/**
* 获取list缓存 - 根据索引位置
*
* @param key 键值
* @param i   索引位置
* @return
*/
public Object getCacheList(String key, int i) {
BoundListOperations listOps = redisTemplate.boundListOps(key);
return listOps.index(i);
}

/**
* 获取总条数, 可用于分页
*
* @param key
* @return
*/
public long getCacheListSize(String key) {
BoundListOperations listOps = redisTemplate.boundListOps(key);
return listOps.size();
}
}


4. 在service中引入使用工具类操作redis
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: