Java spring uses RedisTemplate to operate Redis database

1. What is Redis

Redis is a non-relational database with high access performance. It is generally used as a cache database to reduce the pressure of normal storage of the database.

Redis can store the mapping between keys and 5 different data structure types. The 5 data structure types are String (string), List (list), Set (collection), Hash (hash) and Zset (ordered). set).

Here is a brief introduction to these five data structure types:
Insert picture description here

Two. RedisTemplate and related methods

1. RedisTemplate
Spring encapsulates the RedisTemplate object to perform various operations on Redis, and it supports all Redis native APIs. RedisTemplate is located under the spring-data-redis package. RedisTemplate provides various redis operations, exception handling and serialization, supports publish and subscribe, and implements spring 3.1 cache. RedisTemplate provides various redis operations, exception handling and serialization, supports publish and subscribe, and implements spring 3.1 cache. RedisTemplate provides various redis operations, exception handling and serialization, supports publish and subscribe, and implements spring 3.1 cache. RedisTemplate provides various redis operations, exception handling and serialization, supports publish and subscribe, and implements spring 3.1 cache.
Insert picture description here

Note that RedisTemplate is a template class whose key and value are both generic. In general, the key is of type String, such as: RedisTemplate<String,Object>.

In addition, if there are no special circumstances, do not define it as RedisTemplate<Object, Object>, otherwise it will cause type errors when used according to the Richter substitution principle.

spring-data-redis provides the following functions for jedis:
1. Automatic connection pool management, providing a highly encapsulated "RedisTemplate" class
2. Classifying and encapsulating a large number of APIs in the jedis client, encapsulating the same type of operation as Operation interface
ValueOperations: simple KV operation

       SetOperations:set类型数据操作

       ZSetOperations:zset类型数据操作

       HashOperations:针对map类型的数据操作

       ListOperations:针对list类型的数据操作
       ```
2.RedisTemplate中定义了对5种数据结构操作
```c
redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set
opsForXXX和boundXXXOps的区别?

XXX is the type of value. The former obtains an operator, but does not specify the operation object (key), and can operate multiple keys and corresponding values ​​within a connection (transaction); the latter obtains a specified operation object (key) operator, can only operate the value corresponding to this key within a connection (transaction).

There is a bug in the counting API (increment), you need to pay attention to it. After counting through the increment, when you get the count value through the get method, an EOF exception may be thrown (related to the local jdk and redis compiled version). Consider using boundValueOps(key).get(0,-1) to get the count value.

3. Specific examples of RedisTemplate operating Redis database

1. Value type operation:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class TestValue {
    
    
    @Autowired
    private RedisTemplate redisTemplate;    
    @Test
    public void setValue(){
    
    
//存值,针对值类型,ops相当于options
        redisTemplate.boundValueOps("name").set("itcast");      
    }   
    @Test
    public void getValue(){
    
    
        String str = (String) redisTemplate.boundValueOps("name").get();
        System.out.println(str);
    }   
    @Test
    public void deleteValue(){
    
    
        redisTemplate.delete("name");
    }   
}

2. The Set type of the set type operation is unordered, that is, the access sequence is not necessarily the same

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class TestSet {
    
    
     
    @Autowired
    private RedisTemplate redisTemplate;
     
    /**
     * 存入值
     */
    @Test
    public void setValue(){
    
    
        redisTemplate.boundSetOps("nameset").add("曹操");     
        redisTemplate.boundSetOps("nameset").add("刘备"); 
        redisTemplate.boundSetOps("nameset").add("孙权");
    }
     
    /**
     * 提取值
     */
    @Test
    public void getValue(){
    
    
        Set members = redisTemplate.boundSetOps("nameset").members();
        System.out.println(members);
    }
     
    /**
     * 删除集合中的某一个值
     */
    @Test
    public void deleteValue(){
    
    
        redisTemplate.boundSetOps("nameset").remove("孙权");
    }
     
    /**
     * 删除整个集合
     */
    @Test
    public void deleteAllValue(){
    
    
        redisTemplate.delete("nameset");
    }
}

Output result: [Sun Quan, Liu Bei, Cao Cao], in addition, elements of set type cannot be repeated. When the set has no value, it will return a []
3. List type operation

The list type is divided into two types, one is the left push stack, the other is the right push stack

Push the stack right:

/**
 * 右压栈:后添加的对象排在后边,相当于队列,相当于先进先出
 */
@Test
public void testSetValue1(){
    
            
    redisTemplate.boundListOps("namelist1").rightPush("刘备");
    redisTemplate.boundListOps("namelist1").rightPush("关羽");
    redisTemplate.boundListOps("namelist1").rightPush("张飞");        
}
 
/**
 * 显示右压栈集合,range 表示查询的索引,从第几个查到第几个,如果想查询所有的数的话只能将第二个数写得大一点。
 */
@Test
public void testGetValue1(){
    
    
    List list = redisTemplate.boundListOps("namelist1").range(0, 10);
    System.out.println(list);
}

Running result: [Liu Bei, Guan Yu, Zhang Fei], elements can be repeated

Push the stack left:

/**
 * 左压栈:后添加的对象排在前边,相当于栈,先进后出
 */
@Test
public void testSetValue2(){
    
            
    redisTemplate.boundListOps("namelist2").leftPush("刘备");
    redisTemplate.boundListOps("namelist2").leftPush("关羽");
    redisTemplate.boundListOps("namelist2").leftPush("张飞");     
}
 
/**
 * 显示左压栈集合
 */
@Test
public void testGetValue2(){
    
    
    List list = redisTemplate.boundListOps("namelist2").range(0, 10);
    System.out.println(list);
}

Running results: [Zhang Fei, Guan Yu, Liu Bei]

Query elements based on index

/**
 * 查询集合某个元素
 */
@Test
public void testSearchByIndex(){
    
    
    String s = (String) redisTemplate.boundListOps("namelist1").index(1);
    System.out.println(s);
}

Operation result: return the value of the element whose index is 1 and remove an element

/**
 * 移除集合某个元素,其中remove中第一个参数是移除的个数
 */
@Test
public void testRemoveByIndex(){
    
    
    redisTemplate.boundListOps("namelist1").remove(1, "关羽");
}

This means removing a "Guan Yu".

4. Hash type operation

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestHash {
    
    
  @Autowired
  private RedisTemplate redisTemplate;
  
  //  存值
  @Test
  public void testSetValue() {
    
    
    redisTemplate.boundHashOps("namehash").put("a", "唐僧");
    redisTemplate.boundHashOps("namehash").put("b", "悟空");
    redisTemplate.boundHashOps("namehash").put("c", "八戒");
    redisTemplate.boundHashOps("namehash").put("d", "沙僧");
  }
  
  //获取所有的key
  @Test
  public void testGetKeys() {
    
    
    Set s = redisTemplate.boundHashOps("namehash").keys();
    System.out.println(s);
  }
  
  //  获取所有的value
  @Test
  public void testGetValues() {
    
    
    List values = redisTemplate.boundHashOps("namehash").values();
    System.out.println(values);
  }
  
  //  根据key获取值
  @Test
  public void testGetValueByKey() {
    
    
    Object object = redisTemplate.boundHashOps("namehash").get("b");
    System.out.println(object);
  }
  
  //根据key移除值
  @Test
  public void testRemoveValueByKey() {
    
    
    redisTemplate.boundHashOps("namehash").delete("c");
  }
  
}

Four. The difference between RedisTemplate and StringRedisTemplate

The relationship between the two is that StringRedisTemplate inherits RedisTemplate.

The data of the two are not common; that is to say, StringRedisTemplate can only manage data in StringRedisTemplate, and RedisTemplate can only manage data in RedisTemplate.

There are two serialization strategies adopted by SDR by default, one is the serialization strategy of String, and the other is the serialization strategy of JDK.

StringRedisTemplate adopts the String serialization strategy by default, and the saved keys and values ​​are serialized and saved using this strategy.

RedisTemplate uses the JDK serialization strategy by default, and the saved keys and values ​​are serialized and saved using this strategy.

The sequence class used by RedisTemplate is in the operation of data, for example, when the data is stored, the data will be serialized into a byte array and then stored in the Redis database. At this time, when you open Redis to view, you will see that your data is not in It is displayed in a readable form, but in a byte array, similar to the following
Insert picture description here

Of course, when obtaining data from Redis, the data will be converted as a byte array by default. This will cause a problem. When the data that needs to be obtained is not stored in redis as a byte array but is a normal readable string, For example, the following form
Insert picture description here

Guess you like

Origin blog.csdn.net/dcj19980805/article/details/115179473