我们知道,Redis共有5种数据类型,分别是String.List.Set.Hash.Zset,前面对这几个类型分别做了介绍,那么在Java中我们如何操作Redis呢,是使用spring封装的RedisTemplate,本文介绍RedisTemplate如何来操作Redis。


1.RedisTemplate
1
public class RedisTemplate<K, V> extends RedisAccessor implements RedisOperations<K, V>

我们可以看到RedisTemplate是一种泛型定义的类型,它继承于RedisAccessor类,实现了RedisOperations接口,这个接口主要定义了操作redis数据的一些方式。我们先着重分析下RedisAccessor的实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class RedisAccessor implements InitializingBean {

private RedisConnectionFactory connectionFactory;

public void afterPropertiesSet() {
Assert.notNull(getConnectionFactory(), "RedisConnectionFactory is required");
}

/**
* Returns the connectionFactory.
*
* @return Returns the connectionFactory
*/
public RedisConnectionFactory getConnectionFactory() {
return connectionFactory;
}

/**
* Sets the connection factory.
*
* @param connectionFactory The connectionFactory to set.
*/
public void setConnectionFactory(RedisConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
}

我们可以看出RedisAccessor实现了InitializingBean这个接口,这个是spring容器初始化时所用到的接口,这个接口的作用是,在bean是初始化时,如果bean实现了InitializingBean接口,则会自动调用afterPropertiesSet方法。关于如何实现需查看spring源码…
那么由此我们可以得知由于RedisTemplate实现了InitializingBean接口,那么在初始化该bean时,将会获得connectionFactory对象,并且connectionFactory通过set注入。由此我们获得了Redis的连接工厂即连接。

2.RedisTemplate中定义了对5种数据结构操作

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

2.1 redisTemplate.opsForList()

opsForList()返回的是ListOperations<K, V>的类型,ListOperations中定义了一些对List数据类型的操作方式。

  • List range(K key, final long start, final long end)
    返回存储在键中的列表的指定元素。偏移开始和停止是基于零的索引,其底层调用connection.lRange(rawKey, start, end)。
  • Long remove(K key, long count, Object value);从存储在键中的列表中删除等于值的元素的第一个计数事件。
    计数参数以下列方式影响操作:
    count> 0:删除等于从头到尾移动的值的元素。
    count <0:删除等于从尾到头移动的值的元素。
    count = 0:删除等于value的所有元素。
  • V index(K key, long index);根据下表获取列表中的值,下标是从0开始的
  • leftPush leftPop rightPush rightPop都是类似的
2.2 redisTemplate.opsForHash()

public interface HashOperations<H,HK,HV>,HK代表hash的键值,HV代表hash的value值

  • void put(H key, HK hashKey, HV value);
  • void putAll(H key, Map<? extends HK, ? extends HV> m);
  • HV get(H key, Object hashKey);
  • Boolean hasKey(H key, Object hashKey);
  • Long delete(H key, Object… hashKeys);
2.3 redisTemplate.opsForSet()

Redis的Set是string类型的无序集合。集合成员是唯一的,这就意味着集合中不能出现重复的数据。
Redis 中 集合是通过哈希表实现的,所以添加,删除,查找的复杂度都是O(1)。
public interface SetOperations<K,V>
SetOperations提供了对无序集合的一系列操作:
常用的添加和删除可以查看api,这里就不再赘述。