SpringBoot学习笔记:整合redis

Posted 听风者-better

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot学习笔记:整合redis相关的知识,希望对你有一定的参考价值。

本文介绍springboot整合redis

1.引入依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-pool2</artifactId>
</dependency>

2.添加配置

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password: 123456
    timeout: 3000
    database: 0
    # 默认情况下spring-data-redis使用lettuce,你可以替换为jedis
    lettuce:
      pool:
        max-active: 8
        max-idle: 10
        min-idle: 5
        max-wait: 1ms
      shutdown-timeout: 1000ms

3.RedisTemplate个性化

默认提供 RedisTemplate StringRedisTemplate 这两个模板去进行开发
StringRedisTemplate 主要是字符串的缓存,序列化用默认的即可
RedisTemplate 主要是对象的缓存,默认为Jdk序列化,我们可以自己配置,使用JSON序列化

@Configuration
public class RedisConfig 

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

    private Jackson2JsonRedisSerializer<Object> initJacksonSerializer() 
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        return jackson2JsonRedisSerializer;
    

4.各个类型的常用api

@Autowired
private RedisTemplate redisTemplate;

@Test
void redisString() 
    ValueOperations valueOperations = redisTemplate.opsForValue();
    //添加元素
    valueOperations.set("twy", "唐万言");
    //添加元素设置过期时间
    valueOperations.set("timeout", "过期时间", 30L, TimeUnit.SECONDS);
    //获取元素
    String value = (String) valueOperations.get("twy");
    log.info("获取元素:" + value);
    //移除元素
    valueOperations.getOperations().delete("twy");

    //计数
    valueOperations.increment("number");
    valueOperations.increment("number", 10L);
    valueOperations.decrement("number");
    valueOperations.decrement("number", 5L);


@Test
void redisHash() 
    HashOperations hashOperations = redisTemplate.opsForHash();

    //添加元素
    hashOperations.put("key", "filed", "value");
    hashOperations.put("key", "filed2", "value2");

    //获取元素
    String value = (String) hashOperations.get("key", "filed");
    log.info("获取元素:" + value);

    //批量获取元素
    List fileds = Arrays.asList(new String[]"filed", "filed2");
    List<String> list = hashOperations.multiGet("key", fileds);
    list.forEach(x -> log.info("获取元素:" + x));

    //移除元素
    hashOperations.delete("key", "filed", "filed2");

    //设置过期时间
    redisTemplate.expire("key", 30L, TimeUnit.SECONDS);


@Test
void redisList() 
    ListOperations listOperations = redisTemplate.opsForList();

    //添加元素(left-从头开始添加,right-从末尾开始添加)
    listOperations.leftPush("list1", "java1");
    listOperations.leftPush("list1", "java2");
    listOperations.leftPush("list1", "java1");
    listOperations.leftPush("list1", "java2");
    listOperations.rightPush("list1", "c++");
    listOperations.rightPush("list1", ".net");
    listOperations.rightPush("list1", "python");
    listOperations.rightPush("list1", "vue");

    //添加整个list集合
    listOperations.leftPushAll("list2", Arrays.asList(new String[]"one", "two", "three"));
    listOperations.rightPushAll("list2", Arrays.asList(new String[]"1", "2", "3"));

    //获取集合长度
    Long size = listOperations.size("list1");
    log.info("集合长度:" + size);

    //获取集合
    List<String> list1 = listOperations.range("list1", 0L, size - 1);
    List<String> list2 = listOperations.range("list1", 0L, -1);
    list1.forEach(x -> log.info("元素:" + x));
    list2.forEach(x -> log.info("元素:" + x));

    //根据下标获取元素
    String index = (String) listOperations.index("list1", 1L);
    log.info(index);

    //根据下标修改元素
    listOperations.set("list1", 1L, "python");
    log.info((String) listOperations.index("list1", 1L));

    //移除元素(删除"java1"的元素2次)
    listOperations.remove("list1", 2L, "java1");

    //保留范围内的元素
    listOperations.trim("list1", 1L, 2L);


@Test
void redisSet() 
    SetOperations setOperations = redisTemplate.opsForSet();
    //添加元素
    setOperations.add("key", "value");
    setOperations.add("key", "value1");
    setOperations.add("key2", "value2");
    setOperations.add("key2", "value3");
    //获取元素
    Set value = setOperations.members("key");
    value.forEach(x->log.info(x.toString()));
    //删除元素
    setOperations.remove("key","value");
    //判断元素是否存在
    Boolean flag = setOperations.isMember("key", "value");
    log.info(flag.toString());
    //集合运算
    //并集
    Set values = setOperations.union("key", "key2");
    values.forEach(x -> log.info("并集" + x.toString()));
    //交集
    Set values2 = setOperations.intersect("key", "key2");
    values2.forEach(x -> log.info("交集" + x.toString()));
    //返回集合key1中存在,但是key2中不存在的数据集合
    Set values3 = setOperations.difference("key", "key2");
    values3.forEach(x -> log.info("差异" + x.toString()));


@Test
void redisZSet() 
    ZSetOperations zSetOperations = redisTemplate.opsForZSet();
    //添加元素
    zSetOperations.add("key", "value1", 1);
    zSetOperations.add("key", "value2", 2);
    zSetOperations.add("key", "value2", 2);
    zSetOperations.add("key", "value3", 3);
    //删除元素
    zSetOperations.remove("key", "value1");
    //修改score
    zSetOperations.incrementScore("key", "value2", -1);
    //获取score
    Double d = zSetOperations.score("key", "value2");
    log.info(d.toString());
    //获取排名
    Long rank = zSetOperations.rank("key", "value3");
    log.info("获取排名:" + rank);
    //获取集合大小
    Long size = zSetOperations.size("key");
    Long zCard = zSetOperations.zCard("key");
    log.info("获取集合大小:" + size);
    log.info("获取集合大小:" + zCard);
    //获取集合元素
    Set zSet = zSetOperations.range("key", 0L, -1L);
    zSet.forEach(x -> log.info(x.toString()));

以上是关于SpringBoot学习笔记:整合redis的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot学习—— springboot快速整合Redis

springboot整合redis

SpringBoot整合EHcache学习笔记

微服务SpringBoot 整合Redis 实现点赞点赞排行榜

SpringBoot学习—— springboot快速整合Redis

springboot整合jedis