springboot调用redis数据库,操作字符串

1.maven导入SpringDataRedis

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

2.config/RedisConfiguration.class

package com.sky.config;

import lombok.extern.slf4j.Slf4j;
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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@Slf4j
public class RedisConfiguration {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        // 设置序列化器
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        return template;
    }
}

3.写测试类,来操作redis/:SpringDataRedisTest

package com.sky.test;

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.*;

import java.util.concurrent.TimeUnit;

@SpringBootTest
public class SpringDataRedisTest {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Test
    public void testSpringDataRedis() {
        // 这里可以编写测试代码,验证Spring Data Redis的功能
        System.out.println("RedisTemplate: " + redisTemplate);
        // 例如,测试RedisTemplate的基本操作
        // 可以使用@Autowired注入RedisTemplate并进行操作
        ValueOperations<String, Object> value = redisTemplate.opsForValue();
        ListOperations<String, Object> list = redisTemplate.opsForList();
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
    }

    @Test
    public void testRedis() {
        ValueOperations<String, Object> value = redisTemplate.opsForValue();
        // 设置code为135790,有效期1分钟,如果不存在则设置,存在则不做任何操作
        redisTemplate.opsForValue().setIfAbsent("code", 135790,  1, TimeUnit.MINUTES);
        // 设置code为135790,有效期1分钟,存在就修改,不存在就添加
        redisTemplate.opsForValue().set("code", 135790,  1, TimeUnit.MINUTES);
        value.set("city", "北京");
        // 获取code的值
        System.out.println(value.get("city"));
    }
}

你可能感兴趣的:(数据库,spring,boot,redis,spring)