SpringBoot Data Redis to operate Redis

Disclaimer: Without permission, it is forbidden to reproduce in any form. If you want to quote, please mark the link address. The full text is 4277 words in total, and it takes about 1 minute to read. For
more learning content, welcome to follow my personal public account: Programmer who doesn't understand development

1. Redis startup

The main role of Redis

Cooperate with relational database for cache

Various data structures store persistent data

installation location

CentOS 7

start up

start redis

cd /usr/local/bin
redis-server /etc/redis.conf
ps -ef | grep redis

close redis

redis-cli shutdown

Enter the client

redis-cli

Test connection
After entering the client, enter:

ping

2. Operate Redis in Java

<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
@Test
public void testRedis(){
    
    
    // 1、获取连接
    Jedis jedis = new Jedis("192.168.10.129", 6379);

    // 2、执行具体操作
    //添加一个[key, value]
    jedis.set("username", "张三");

    // 获取value
    String username = jedis.get("username");
    System.out.println("username = " + username);

    //删除
    jedis.del("username");
    System.out.println("username = " + username);

    // 存hashset
    jedis.hset("myhashset", "addr","beijing");
    String hget = jedis.hget("myhashset", "addr");
    System.out.println("hget = " + hget);

    // 3、关闭连接
    jedis.close();
}

3. Spring Data Redis (emphasis)

pom

<!--开启redis缓存-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

application.yaml

spring:
  redis:
    host: 192.168.10.129
#    port: 6379 #不写就是默认端口号6379
#    database: 0 #操作的是0号数据库,不写就是默认的

RedisTemplate

insert image description here

test connection

package com.jerry.springdataredis;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

@SpringBootTest
class SpringdataredisApplicationTests {
    
    

    @Autowired
    RedisTemplate redisTemplate;

    @Test
    void testString() {
    
    
        redisTemplate.opsForValue().set("city","beijing");

    }

}

Looking at the redis database, you will find that there are a bunch of escape characters in front of [key, values], because the default RedisTemplate has been serialized

insert image description here

Configure the Redis serializer

To solve this problem, we need to manually add configuration classes and set our own serializers

package com.jerry.springdataredis.config;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    
    

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
    
    
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();

        //默认的Key序列化器为:JdkSerializationRedisSerializer
        redisTemplate.setKeySerializer(new StringRedisSerializer()); // key序列化
        //redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); // value序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer()); // hash序列化

        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }
}

insert image description here

insert image description here

redisTemplate operates common data types

package com.jerry.springdataredis;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@SpringBootTest
class SpringdataredisApplicationTests {
    
    

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 操作 String 类型的数据
     */
    @Test
    void testString() {
    
    
        redisTemplate.opsForValue().set("city123","beijing123");

        Object o = redisTemplate.opsForValue().get("city123");
        System.out.println("o = " + o);

        redisTemplate.opsForValue().set("k1", "v1", 10L, TimeUnit.SECONDS);

        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("k1", "v1");
        System.out.println("aBoolean = " + aBoolean);

    }

    /**
     * 操作 Hash 类型的数据
     */
    @Test
    void testHash(){
    
    
        // 存值
        redisTemplate.opsForHash().put("001", "name", "xiaoming");
        redisTemplate.opsForHash().put("001", "age", "20");
        redisTemplate.opsForHash().put("001", "city", "Shanghai");

        // 取值
        String name = (String) redisTemplate.opsForHash().get("001", "name");
        System.out.println("name = " + name);

        // 获取hash结构中的所有字段
        Set keys = redisTemplate.opsForHash().keys("001");
        for (Object key : keys) {
    
    
            System.out.println(key);
        }

        // 获取hash结构中的所有值
        List values = redisTemplate.opsForHash().values("001");
        for (Object value : values) {
    
    
            System.out.println(value);
        }
    }

    /**
     * 操作 List 类型的数据(有序集合)
     */
    @Test
    void testList(){
    
    
        // 存值
        redisTemplate.opsForList().leftPush("myList", "a");
        redisTemplate.opsForList().leftPushAll("myList", "b","c","d");

        // 取值
        List<String> myList = redisTemplate.opsForList().range("myList", 0, -1);
        for (String value : myList) {
    
    
            System.out.println(value); // d c b a
        }

        // 获取列表长度
        Long size = redisTemplate.opsForList().size("myList");
        int isize = size.intValue();

        for (int i = 0; i < isize; i++) {
    
    
            // 出队列
            String element = (String) redisTemplate.opsForList().rightPop("myList");
            System.out.println(element); // a b c d
        }

    }

    /**
     * 操作set类型数据(无序集合,可以重复)
     */
    @Test
    void testSet(){
    
    
        // 存值, 可以有重复的元素
        redisTemplate.opsForSet().add("mySet","a","b","c","a","b");

        // 取值
        Set<String> mySet = redisTemplate.opsForSet().members("mySet");
        for (String s : mySet) {
    
    
            System.out.println(s); // c b a
        }
        // 删除元素
        redisTemplate.opsForSet().remove("mySet", "a","b");
    }


    /**
     * 操作 ZSet 类型数据(有序集合,按分数大小排序)
     */
    @Test
    void testZSet(){
    
    
        // 存值, 不能有重复的元素
        redisTemplate.opsForZSet().add("myZSet", "a", 10.0);
        redisTemplate.opsForZSet().add("myZSet", "b", 11.0);
        redisTemplate.opsForZSet().add("myZSet", "c", 12.0);
        redisTemplate.opsForZSet().add("myZSet", "a", 13.0);

        // 取值
        Set<String> myZSet = redisTemplate.opsForZSet().range("myZSet", 0, -1);
        for (String s : myZSet) {
    
    
            System.out.println(s); // b c a
        }
        System.out.println();

        // 修改分数
        redisTemplate.opsForZSet().incrementScore("myZSet", "b", 20.0);

        myZSet = redisTemplate.opsForZSet().range("myZSet", 0, -1);
        for (String s : myZSet) {
    
    
            System.out.println(s); // c a b
        }
        System.out.println();

        // 删除元素
        redisTemplate.opsForZSet().remove("myZSet", "a","b");

        myZSet = redisTemplate.opsForZSet().range("myZSet", 0, -1);
        for (String s : myZSet) {
    
    
            System.out.println(s); // c
        }
    }
}

Universal operations, which can be operated on different data types

/**
 * 通用操作,针对不同的数据类型都可以操作
 */
@Test
void testCommon(){
    
    
    // 获取redis中所有的key
    Set<String> keys = redisTemplate.keys("*");
    for (String key : keys) {
    
    
        System.out.println(key);
    }

    // 判断指定key 是否存在
    Boolean hasKey = redisTemplate.hasKey("jerry");
    System.out.println("hasKey = " + hasKey);

    // 删除指定 key
    redisTemplate.delete("myZSet");

    // 获取指定key 对应的value的数据类型
    DataType dataType = redisTemplate.type("mySet");
    System.out.println(dataType.name());
}

–end–

Guess you like

Origin blog.csdn.net/qq_44807756/article/details/129179170