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

spring-data-redis整合以及基本操作

2017-09-07 00:00 603 查看
摘要: redis与spring整合到一起使用,spring提供的专门的模板方法

整合包使用maven管理



使用properties资源文件存储redis连接信息

# Redis settings
redis.host=192.168.4.246
redis.port=6390
redis.pass=qzgtest

redis.maxIdle=300
redis.maxActive=600
redis.maxWait=1000
redis.testOnBorrow=true


spring需要配置jedis连接配置信息、连接工厂以及模板对象

<!-- 引入配置文件 -->
<context:property-placeholder location="classpath:redis.properties"/>

<!-- 创建redis连接池 -->
<bean name="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="${redis.testOnBorrow}" />
</bean>
<!-- redis连接工厂 -->
<bean name="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="poolConfig" ref="jedisPoolConfig"></property>
<property name="hostName" value="${redis.host}"></property>
<property name="port" value="${redis.port}"></property>
<property name="password" value="${redis.pass}"></property>
</bean>

<!-- spring提供的模板对象 -->
<bean name="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"></property>
</bean>


写了一个通用工具类对String类型和hash类型操作做了封装

public class RedisUtil	{

@Autowired
private RedisTemplate<String, String> template;

//设置string
public void set(String key ,String value){
template.opsForValue().set(key, value);
}

//设置String和超时时间
public void set(String key ,String value,Long timeout){
template.opsForValue().set(key, value);
template.boundValueOps(key).expire(timeout, TimeUnit.HOURS);
}

//获取数据
public String get(String key){
return template.opsForValue().get(key);
}

//设置hash
public void hset(String hash ,String key,String value){
template.opsForHash().put(hash, key, value);
}

//设置hash和超时时间
public void hset(String hash ,String key,String value,Long timeout){
template.opsForHash().put(hash, key, value);
//设置过期时间单位小时
template.boundHashOps(hash).expire(timeout, TimeUnit.HOURS);
}

//获取hash下所有键和值
public Map<String,String> hgetAll(String keys){
HashOperations<String, Object, Object> opsForHash = template.opsForHash();
Map<String,String> keyAndValue = new HashMap<String, String>();

Set<Object> set =opsForHash.keys(keys);
for (Object obj : set) {
String key =  (String) obj;
String value =(String) opsForHash.get(keys, key);
keyAndValue.put(key, value);
}
return keyAndValue;
}

//获取hash下单个值
public String hget(String keys,String key){
return (String) template.opsForHash().get(keys, key);
}


模板对象提供了两种操作redis的模式

一种是opsForXXX方式获取Operations对象,通过对象再来操作

另一种是boundHashOps(XXX)直接获取指定key的redis数据对象,进行操作
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Redis Spring Data Redis