首先解釋一下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(地理位置)以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網之家。
新聞熱點
疑難解答
圖片精選