Spring Data Redis

启动指令

redis-server.exe redis.windows.conf

1.导入Spring Data Redis的maven坐标

在pom.xml中添加依赖

        
            org.springframework.boot
            spring-boot-starter-data-redis
        

2.配置Redis数据源

在yml文件中配置相应的数据源

  redis:
    host: localhost
    port: 6379
    password: 123456

3.编写配置类,创建RedisTemplate对象

@Configuration
@Slf4j
public class RedisConfiguration {
    
    @Bean//声明了bean会在启动时自动执行 redisConnectionFactory由starter自动创建无需自己创建
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        log.info("开始创建redis模板对象..");
        RedisTemplate redisTemplate = new RedisTemplate();
        //设置redis的连接工厂对象
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //设置redis key的序列化器
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }
}

4.通过RedisTemplate对象操作Redis

@SpringBootTest
public class SpringDataRedisTest {
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testRedisTemplate() {
        System.out.println(redisTemplate);
        //对应操作String类型
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //对应操作Hash类型
        HashOperations hashOperations = redisTemplate.opsForHash();
        //对应操作list类型
        ListOperations listOperations = redisTemplate.opsForList();
        //对应操作集合类型
        SetOperations setOperations = redisTemplate.opsForSet();
        //对应操作有序集合类型
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();
    }

    /**
     * 操作字符串类型的数据
     */
    @Test
    public void setStringOper() {
        System.out.println(redisTemplate);
        //set get setx setnx
        redisTemplate.opsForValue().set("city", "北京");
        Object city = redisTemplate.opsForValue().get("city");
        System.out.println(city);
        redisTemplate.opsForValue().set("code", "1234", 30, TimeUnit.SECONDS);
        redisTemplate.opsForValue().setIfAbsent("li", 1);
        redisTemplate.opsForValue().setIfAbsent("li", 2);
    }

    /**
     * 操作哈希类型的数据
     */
    @Test
    public void testHash() {
        //hset hget hkeys hvals
        HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.put("200", "name", "alan");
        hashOperations.put("200", "age", "12");
        System.out.println(hashOperations.keys("200"));
        System.out.println(hashOperations.values("200"));
        hashOperations.delete("200","name");
    }
}

你可能感兴趣的:(spring,redis,bootstrap)