首先解釋一下Lettuce客戶(hù)端:
Lettuce 和 Jedis 的都是連接Redis Server的客戶(hù)端程序。Jedis在實(shí)現(xiàn)上是直連redis server,多線(xiàn)程環(huán)境下非線(xiàn)程安全,除非使用連接池,為每個(gè)Jedis實(shí)例增加物理連接。Lettuce基于Netty的連接實(shí)例(StatefulRedisConnection),可以在多個(gè)線(xiàn)程間并發(fā)訪(fǎng)問(wèn),且線(xiàn)程安全,滿(mǎn)足多線(xiàn)程環(huán)境下的并發(fā)訪(fǎng)問(wèn),同時(shí)它是可伸縮的設(shè)計(jì),一個(gè)連接實(shí)例不夠的情況也可以按需增加連接實(shí)例。
1、添加依賴(lài)
<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 # 連接超時(shí)時(shí)間(毫秒) timeout: 1000 # Redis默認(rèn)情況下有16個(gè)分片,這里配置具體使用的分片,默認(rèn)是0 database: 0 # 連接池配置 lettuce: pool: # 連接池最大連接數(shù)(使用負(fù)值表示沒(méi)有限制) 默認(rèn) 8 max-active: 8 # 連接池最大阻塞等待時(shí)間(使用負(fù)值表示沒(méi)有限制) 默認(rèn) -1 max-wait: -1 # 連接池中的最大空閑連接 默認(rèn) 8 max-idle: 8 # 連接池中的最小空閑連接 默認(rèn) 0 min-idle: 0
3、實(shí)現(xiàn)邏輯
@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; }測(cè)試結(jié)果:


由于redis有String、list、set、zset、hash、geo等類(lèi)型,因此使用時(shí)不止使用opsForValue()方法,具體的對(duì)應(yīng)方法如下:
opsForValue: 對(duì)應(yīng) String(字符串) opsForZSet: 對(duì)應(yīng) ZSet(有序集合) opsForHash: 對(duì)應(yīng) Hash(哈希) opsForList: 對(duì)應(yīng) List(列表) opsForSet: 對(duì)應(yīng) Set(集合) opsForGeo: 對(duì)應(yīng) GEO(地理位置)以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)之家。
新聞熱點(diǎn)
疑難解答
圖片精選