SpringBoot--整合Lettuce redis


首先解釋一下Lettuce客戶端:

  Lettuce 和 Jedis 的都是連接Redis Server的客戶端程序。Jedis在實現上是直連redis server,多線程環境下非線程安全,除非使用連接池,為每個Jedis實例增加物理連接。Lettuce基於Netty的連接實例(StatefulRedisConnection),可以在多個線程間並發訪問,且線程安全,滿足多線程環境下的並發訪問,同時它是可伸縮的設計,一個連接實例不夠的情況也可以按需增加連接實例。

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、添加redis配置

spring:
  redis:
      host: ****
      password:****
      port: 6379
  # 連接超時時間(毫秒)
      timeout: 1000
  # Redis默認情況下有16個分片,這里配置具體使用的分片,默認是0
      database: 0
  # 連接池配置
      lettuce:
        pool:
  # 連接池最大連接數(使用負值表示沒有限制) 默認 8
          max-active: 8
  # 連接池最大阻塞等待時間(使用負值表示沒有限制) 默認 -1
          max-wait: -1
  # 連接池中的最大空閑連接 默認 8
          max-idle: 8
  # 連接池中的最小空閑連接 默認 0
          min-idle: 0

3、實現邏輯

@Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String testRedis(){

        ExecutorService executorService = Executors.newFixedThreadPool(1000);
        IntStream.range(0, 1000).forEach(i -> executorService.execute(() -> stringRedisTemplate.opsForValue().increment("lcl",1)));

        System.out.println("lcl1=============" + stringRedisTemplate.opsForValue().get("lcl"));

        stringRedisTemplate.opsForValue().set("lcl1","val1");

        String val1 = stringRedisTemplate.opsForValue().get("lcl1");

        System.out.println("lcl1=============" + val1);

        String key = "redis:test:demo1";


        User user = new User();
        user.setId(100L);
        user.setUsername("u2");
        user.setPassword("p2");
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(user));

        String valUser = stringRedisTemplate.opsForValue().get(key);
        System.out.println("redis:test:demo1=============" + valUser);

        User getUser = JSON.parseObject(valUser, User.class);

        System.out.println("redis:test:demo1=============" + getUser.getUsername()+ "========" + getUser.getPassword());

        return null;
    }

測試結果:

 

 

 

 

 

 由於redis有String、list、set、zset、hash、geo等類型,因此使用時不止使用opsForValue()方法,具體的對應方法如下:

    opsForValue: 對應 String(字符串)

    opsForZSet: 對應 ZSet(有序集合)

    opsForHash: 對應 Hash(哈希)

    opsForList: 對應 List(列表)

    opsForSet: 對應 Set(集合)

    opsForGeo: 對應 GEO(地理位置)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM