Redis常用命令对应的Spring中RedisTemplate操作方法

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/groggy_puppy/article/details/83379948

1、Spring配置文件:

<?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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	
	
	<!-- 配置jedisPoolConfig -->
	<bean id ="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxIdle" value="50"></property>
		<property name="maxTotal" value="100"></property>
		<property name="maxWaitMillis" value="20000"></property>
	</bean>
	<!-- 配置JedisConnectionFactory -->
	<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
		<property name="hostName" value="your own hostname dude"></property>
		<property name="port" value="6379"></property>
		<property name="poolConfig" ref="poolConfig"></property>
	</bean>
	<!-- 配置SpringRedisTemplate -->
	<!-- 配置序列化规则 -->
	<bean id="jdkServializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
	<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<property name="connectionFactory" ref="connectionFactory"></property>
		<property name="keySerializer" ref="stringRedisSerializer"></property>
		<property name="valueSerializer" ref="stringRedisSerializer"></property>
	</bean>
</beans>

该文件简单配置了redis连接池、连接工厂、序列化规则(根据不同的数据类型修改)和RedisTemplate

2、redis客户端测试:

 

3、使用Spring测试Redis字符串操作

@Test
	public void redisTemplate1(){
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
		RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);
		//设值
		redisTemplate.opsForValue().set("key1", "value1");
		redisTemplate.opsForValue().set("key2", "value2");
		//通过key获取值
		String value1= (String) redisTemplate.opsForValue().get("key1");
		System.out.println(value1);
		redisTemplate.delete("key1");
		//求长度
		Long length = redisTemplate.opsForValue().size("key2");
		System.out.println(length);
		//设置新值并返回旧值
		String oldValue2 = (String) redisTemplate.opsForValue().getAndSet("key2", "new_value2");
		System.out.println(oldValue2);
		//通过key获取值
		String value2 = (String) redisTemplate.opsForValue().get("key2");
		System.out.println(value2);
		//求子串
		String rangeValue2 = (String) redisTemplate.opsForValue().get("key2", 0, 3);
		System.out.println(rangeValue2);
		//追加字符串到末尾,返回新串长度
		int newLen = redisTemplate.opsForValue().append("key2", "_app");
		System.out.println(newLen);
		String appendValue2 = (String) redisTemplate.opsForValue().get("key2");
		System.out.println(appendValue2);
	}

运行结果:

value1
6
value2
new_value2
new_
14
new_value2_app

 

-------------------------------------------------------------------------------------------------------------------------------------------------------
代码主要只是在Spring中操作Redis键值对,其它数据类型直接总结Redis客户端命令对应的RedisTemplate中的方法。

首先要知道,RedisTemplate中定义了对5种数据结构进行操作:

redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set

以下依次给出各类数据类型的Redis客户端命令对应的RedisTemplate中的方法

String类型结构
Redis RedisTemplate rt
set key value rt.opsForValue().set("key","value")
get key rt.opsForValue().get("key")
del key rt.delete("key")
strlen key rt.opsForValue().size("key")
getset key value rt.opsForValue().getAndSet("key","value")
getrange key start end rt.opsForValue().get("key",start,end)
append key value rt.opsForValue().append("key","value")
Hash结构
hmset key field1 value1 field2 value2... rt.opsForHash().putAll("key",map) //map是一个集合对象
hset key field value rt.opsForHash().put("key","field","value")
hexists key field rt.opsForHash().hasKey("key","field")
hgetall key rt.opsForHash().entries("key")  //返回Map对象
hvals key rt.opsForHash().values("key") //返回List对象
hkeys key rt.opsForHash().keys("key") //返回List对象
hmget key field1 field2... rt.opsForHash().multiGet("key",keyList)
hsetnx key field value rt.opsForHash().putIfAbsent("key","field","value"
hdel key field1 field2 rt.opsForHash().delete("key","field1","field2")
hget key field rt.opsForHash().get("key","field")

 

 

 

 

 

 

 

 

 

 

 

 

List结构
lpush list node1 node2 node3...
 
rt.opsForList().leftPush("list","node") 
rt.opsForList().leftPushAll("list",list) //list是集合对象
rpush list node1 node2 node3... rt.opsForList().rightPush("list","node") 
rt.opsForList().rightPushAll("list",list) //list是集合对象
lindex key index rt.opsForList().index("list", index)
llen key rt.opsForList().size("key")
lpop key rt.opsForList().leftPop("key")
rpop key rt.opsForList().rightPop("key")
lpushx list node rt.opsForList().leftPushIfPresent("list","node")
rpushx list node rt.opsForList().rightPushIfPresent("list","node")
lrange list start end rt.opsForList().range("list",start,end)
lrem list count value rt.opsForList().remove("list",count,"value")
lset key index value rt.opsForList().set("list",index,"value")
ltrim key start stop /

有些命令Spring所提供的RedisTemplate并不能支持,比如linsert命令,这个时候可以使用更为底层的方法,如代码:

    try {
			rt.getConnectionFactory().getConnection().lInsert("list".getBytes("utf-8"),
					RedisListCommands.Position.BEFORE, 
					"node2".getBytes("utf-8"), "before_node2".getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
Set结构
sadd key member1 member2... rt.boundSetOps("key").add("member1","member2",...)
rt.opsForSet().add("key", set) //set是一个集合对象
scard key rt.opsForSet().size("key")
sidff key1 key2 rt.opsForSet().difference("key1","key2") //返回一个集合对象
sinter key1 key2 rt.opsForSet().intersect("key1","key2")//同上
sunion key1 key2 rt.opsForSet().union("key1","key2")//同上
sdiffstore des key1 key2 rt.opsForSet().differenceAndStore("key1","key2","des")
sinter des key1 key2 rt.opsForSet().intersectAndStore("key1","key2","des")
sunionstore des key1 key2 rt.opsForSet().unionAndStore("key1","key2","des")
sismember key member rt.opsForSet().isMember("key","member")
smembers key rt.opsForSet().members("key")
spop key rt.opsForSet().pop("key")
srandmember key count rt.opsForSet().randomMember("key",count)
srem key member1 member2... rt.opsForSet().remove("key","member1","member2",...)

 

注意,如果命令中对应RedisTemplate方法中的参数是对象或者字符串,记得修改配置文件中RedisTemplate中属性keySerializer和valueSerializer的值。

另外还有ZSet和HyperLogLog结构命令比较难用并且出现频率不高,有需要再整理。

 

展开阅读全文

没有更多推荐了,返回首页