springboot(十八)redis

78 阅读1分钟

启动

./redis-server.exe

image.png

操作

操持原来窗口不关闭,新开一个窗口

./redis-cli.exe -h 127.0.0.1 -p 6379

image.png

集成到springboot

创建项目

image.png

配置Redis

application.propertiesapplication.yml中配置Redis连接:

spring.redis.host=localhost 
spring.redis.port=6379

创建Redis配置类

创建一个配置类来配置RedisTemplate

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 {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
}

创建测试类

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 java.util.Set;

@SpringBootTest
public class RedisTemplateTest {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Test
    public void testRedisOperations() {
        // Set key-value pairs
        redisTemplate.opsForValue().set("key1", "value1");
        redisTemplate.opsForValue().set("key2", "value2");
        redisTemplate.opsForValue().set("key3", "value3");

        // Get all keys
        Set<String> keys = redisTemplate.keys("*");
        System.out.println("All keys: " + keys);

        // Get single key value
        Object value = redisTemplate.opsForValue().get("key1");
        System.out.println("Value of key1: " + value);

        // Delete a key
        redisTemplate.delete("key2");
        System.out.println("Deleted key2");

        // Verify deletion
        value = redisTemplate.opsForValue().get("key2");
        System.out.println("Value of key2 after deletion: " + value);
    }
}

测试

image.png