电子设备知识网-中国电子设备,国内最专业电子设备平台
电子设备知识网-中国电子设备,国内最专业电子设备平台

Springboot+redis操作多种实现

一、Jedis,Redisson,Lettuce三者的区别共同点:都提供了基于Redis操作的Java API,只是封装程度,具体实现稍有不同。

不同点:

1.1、Jedis

是Redis的Java实现的客户端。支持基本的数据类型如:String、Hash、List、Set、Sorted Set。

1.2、Redisson

优点点:分布式锁,分布式集合,可通过Redis支持延迟队列。

1.3、 Lettuce

用于线程安全同步,异步和响应使用,支持集群,Sentinel,管道和编码器

基于Netty框架的事件驱动的通信层,其方法调用是异步的。Lettuce的API是线程安全的,所以可以操作单个Lettuce连接来完成各种操作。

二、RedisTemplate2.1、使用配置

maven配置引入,(要加上版本号,我这里是因为Parent已声明)

 

<dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-data-redisartifactId> dependency>

application-dev.yml

 

spring: redis: host:192.168.1.140 port:6379 password: database:15#指定redis的分库(共16个0到15)

2.2、使用示例

 

@Resource privateStringRedisTemplatestringRedisTemplate; @Override publicCustomersEntityfindById(Integerid){ //需要缓存 //所有涉及的缓存都需要删除,或者更新 try{ StringtoString=stringRedisTemplate.opsForHash().get(REDIS_CUSTOMERS_ONE,id+“”).toString(); if(toString!=null){ returnJSONUtil.toBean(toString,CustomersEntity.class); } }catch(Exceptione){ e.printStackTrace(); } //缓存为空的时候,先查,然后缓存redis OptionalbyId=customerRepo.findById(id); if(byId.isPresent()){ CustomersEntitycustomersEntity=byId.get(); try{ stringRedisTemplate.opsForHash().put(REDIS_CUSTOMERS_ONE,id+“”,JSONUtil.toJsonStr(customersEntity)); }catch(Exceptione){ e.printStackTrace(); } returncustomersEntity; } returnnull; }

2.3、扩展

2.3.1、spring-boot-starter-data-redis的依赖包

Springboot+redis操作多种实现

3.3.2、stringRedisTemplate API(部分展示)

opsForHash –》 hash操作

opsForList –》 list操作

opsForSet –》 set操作

opsForValue –》 string操作

opsForZSet –》 Zset操作

Springboot+redis操作多种实现

3.3.3 StringRedisTemplate默认序列化机制

 

publicclassStringRedisTemplateextendsRedisTemplate<String,String>{ /** *ConstructsanewStringRedisTemplateinstance.{@link#setConnectionFactory(RedisConnectionFactory)} *and{@link#afterPropertiesSet()}stillneedtobecalled. */ publicStringRedisTemplate(){ RedisSerializerstringSerializer=newStringRedisSerializer(); setKeySerializer(stringSerializer); setValueSerializer(stringSerializer); setHashKeySerializer(stringSerializer); setHashValueSerializer(stringSerializer); } }

三、RedissonClient 操作示例

3.1 基本配置

3.1.1、Maven pom 引入
 

<dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-data-redisartifactId> dependency> <dependency> <groupId>org.redissongroupId> <artifactId>redissonartifactId> <version>3.8.2version> <optional>trueoptional> dependency> <dependency> <groupId>org.redissongroupId> <artifactId>redisson-spring-boot-starterartifactId> <version>LATESTversion> dependency>

3.1.2、添加配置文件Yaml或者json格式

redisson-config.yml

 

#Redisson配置 singleServerConfig: address:“redis://192.168.1.140:6379” password:null clientName:null database:15#选择使用哪个数据库0~15 idleConnectionTimeout:10000 pingTimeout:1000 connectTimeout:10000 timeout:3000 retryAttempts:3 retryInterval:1500 reconnectionTimeout:3000 failedAttempts:3 subscriptionsPerConnection:5 subscriptionConnectionMinimumIdleSize:1 subscriptionConnectionPoolSize:50 connectionMinimumIdleSize:32 connectionPoolSize:64 dnsMonitoringInterval:5000 #dnsMonitoring:false threads:0 nettyThreads:0 codec: class:“org.redisson.codec.JsonJacksonCodec” transportMode:“NIO”

或者,配置 redisson-config.json

 

{ “singleServerConfig”:{ “idleConnectionTimeout”:10000, “pingTimeout”:1000, “connectTimeout”:10000, “timeout”:3000, “retryAttempts”:3, “retryInterval”:1500, “reconnectionTimeout”:3000, “failedAttempts”:3, “password”:null, “subscriptionsPerConnection”:5, “clientName”:null, “address”:“redis://192.168.1.140:6379”, “subscriptionConnectionMinimumIdleSize”:1, “subscriptionConnectionPoolSize”:50, “connectionMinimumIdleSize”:10, “connectionPoolSize”:64, “database”:0, “dnsMonitoring”:false, “dnsMonitoringInterval”:5000 }, “threads”:0, “nettyThreads”:0, “codec”:null, “useLinuxNativeEpoll”:false }

3.1.3、读取配置

新建读取配置类

 

@Configuration publicclassRedissonConfig{ @Bean publicRedissonClientredisson()throwsIOException{ //两种读取方式,Config.fromYAML和Config.fromJSON //Configconfig=Config.fromJSON(RedissonConfig.class.getClassLoader().getResource(“redisson-config.json”)); Configconfig=Config.fromYAML(RedissonConfig.class.getClassLoader().getResource(“redissonconfig.yml“)); returnRedisson.create(config); } }

或者,在 application.yml中配置如下

 

spring: redis: redisson: config:classpath:redisson-config.yaml

3.2 使用示例

 

@RestController @RequestMapping(“/”) publicclassTeController{ @Autowired privateRedissonClientredissonClient; staticlongi=20; staticlongsum=300; //==========================String======================= @GetMapping(“/set/{key}”) publicStrings1(@PathVariableStringkey){ //设置字符 RBucketkeyObj=redissonClient.getBucket(key); keyObj.set(key+“1-v1”); returnkey; } @GetMapping(“/get/{key}”) publicStringg1(@PathVariableStringkey){ //设置字符串 RBucketkeyObj=redissonClient.getBucket(key); Strings=keyObj.get(); returns; } //==========================hash=======================-= @GetMapping(“/hset/{key}”) publicStringh1(@PathVariableStringkey){ Urur=newUr(); ur.setId(MathUtil.randomLong(1,20)); ur.setName(key); //存放Hash RMapss=redissonClient.getMap(“UR”); ss.put(ur.getId().toString(),ur); returnur.toString(); } @GetMapping(“/hget/{id}”) publicStringh2(@PathVariableStringid){ //hash查询 RMapss=redissonClient.getMap(“UR”); Urur=ss.get(id); returnur.toString(); } //查询所有的keys @GetMapping(“/all”) publicStringall(){ RKeyskeys=redissonClient.getKeys(); Iterablekeys1=keys.getKeys(); keys1.forEach(System.out::println); returnkeys.toString(); } //================================读写锁测试============================= @GetMapping(“/rw/set/{key}”) publicvoidrw_set(){ //RedissonLock. RBucketls_count=redissonClient.getBucket(“LS_COUNT”); ls_count.set(“300”,360000000l,TimeUnit.SECONDS); } //减法运算 @GetMapping(“/jf”) publicvoidjf(){ Stringkey=“S_COUNT”; //RAtomicLongatomicLong=redissonClient.getAtomicLong(key); //atomicLong.set(sum); //longl=atomicLong.decrementAndGet(); //System.out.println(l); RAtomicLongatomicLong=redissonClient.getAtomicLong(key); if(!atomicLong.isExists()){ atomicLong.set(300l); } while(i==0){ if(atomicLong.get()>0){ longl=atomicLong.getAndDecrement(); try{ Thread.sleep(1000l); }catch(InterruptedExceptione){ e.printStackTrace(); } i–; System.out.println(Thread.currentThread().getName()+“->”+i+“->”+l); } } } @GetMapping(“/rw/get”) publicStringrw_get(){ Stringkey=“S_COUNT”; Runnabler=newRunnable(){ @Override publicvoidrun(){ RAtomicLongatomicLong=redissonClient.getAtomicLong(key); if(!atomicLong.isExists()){ atomicLong.set(300l); } if(atomicLong.get()>0){ longl=atomicLong.getAndDecrement(); i–; System.out.println(Thread.currentThread().getName()+“->”+i+“->”+l); } } }; while(i!=0){ newThread(r).start(); //newThread(r).run(); //newThread(r).run(); //newThread(r).run(); //newThread(r).run(); } RBucketbucket=redissonClient.getBucket(key); Strings=bucket.get(); System.out.println(“================线程已结束================================”+s); returns; } }

4.3 扩展

4.3.1 丰富的jar支持,尤其是对 Netty NIO框架

4.3.2 丰富的配置机制选择,这里是详细的配置说明

https://github.com/redisson/redisson/wiki/2.-Configuration

关于序列化机制中,就有很多

Springboot+redis操作多种实现Springboot+redis操作多种实现

4.3.3 API支持(部分展示),具体的 Redis –> RedissonClient ,可查看这里

https://github.com/redisson/redisson/wiki/11.-Redis-commands-mapping

Springboot+redis操作多种实现

4.3.4 轻便的丰富的锁机制的实现

Lock

Fair Lock

MultiLock

RedLock

ReadWriteLock

Semaphore

PermitExpirableSemaphore

CountDownLatch

四、基于注解实现的Redis缓存4.1 Maven 和 YML配置

参考 RedisTemplate 配置。另外,还需要额外的配置类

 

//todo定义序列化,解决乱码问题 @EnableCaching @Configuration @ConfigurationProperties(prefix=“spring.cache.redis”) publicclassRedisCacheConfig{ privateDurationtimeToLive=Duration.ZERO; publicvoidsetTimeToLive(DurationtimeToLive){ this.timeToLive=timeToLive; } @Bean publicCacheManagercacheManager(RedisConnectionFactoryfactory){ RedisSerializerredisSerializer=newStringRedisSerializer(); Jackson2JsonRedisSerializerjackson2JsonRedisSerializer=newJackson2JsonRedisSerializer(Object.class); //解决查询缓存转换异常的问题 ObjectMapperom=newObjectMapper(); om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); //配置序列化(解决乱码的问题) RedisCacheConfigurationconfig=RedisCacheConfiguration.defaultCacheConfig() .entryTtl(timeToLive) .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) .disableCachingNullValues(); RedisCacheManagercacheManager=RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); returncacheManager; } }

4.2 使用示例

 

@Transactional @Service publicclassReImplimplementsRedisService{ @Resource privateCustomerRepocustomerRepo; @Resource privateStringRedisTemplatestringRedisTemplate; publicstaticfinalStringREDIS_CUSTOMERS_ONE=“Customers”; publicstaticfinalStringREDIS_CUSTOMERS_ALL=“allList”; //=====================================================================使用Springcahce注解方式实现缓存 //==================================单个操作 @Override @Cacheable(value=“cache:customer”,unless=“null==#result”,key=“#id”) publicCustomersEntitycacheOne(Integerid){ finalOptionalbyId=customerRepo.findById(id); returnbyId.isPresent()?byId.get():null; } @Override @Cacheable(value=“cache:customer”,unless=“null==#result”,key=“#id”) publicCustomersEntitycacheOne2(Integerid){ finalOptionalbyId=customerRepo.findById(id); returnbyId.isPresent()?byId.get():null; } //todo自定义redis缓存的key, @Override @Cacheable(value=“cache:customer”,unless=“null==#result”,key=“#root.methodName+’.’+#id”) publicCustomersEntitycacheOne3(Integerid){ finalOptionalbyId=customerRepo.findById(id); returnbyId.isPresent()?byId.get():null; } //todo这里缓存到redis,还有响应页面是String(加了很多转义符,),不是Json格式 @Override @Cacheable(value=“cache:customer”,unless=“null==#result”,key=“#root.methodName+’.’+#id”) publicStringcacheOne4(Integerid){ finalOptionalbyId=customerRepo.findById(id); returnbyId.map(JSONUtil::toJsonStr).orElse(null); } //todo缓存json,不乱码已处理好,调整序列化和反序列化 @Override @Cacheable(value=“cache:customer”,unless=“null==#result”,key=“#root.methodName+’.’+#id”) publicCustomersEntitycacheOne5(Integerid){ OptionalbyId=customerRepo.findById(id); returnbyId.filter(obj->!StrUtil.isBlankIfStr(obj)).orElse(null); } //==================================删除缓存 @Override @CacheEvict(value=“cache:customer”,key=“‘cacheOne5’+’.’+#id”) publicObjectdel(Integerid){ //删除缓存后的逻辑 returnnull; } @Override @CacheEvict(value=“cache:customer”,allEntries=true) publicvoiddel(){ } @CacheEvict(value=“cache:all”,allEntries=true) publicvoiddelall(){ } //==================List操作 @Override @Cacheable(value=“cache:all”) publicListcacheList(){ Listall=customerRepo.findAll(); returnall; } //todo先查询缓存,再校验是否一致,然后更新操作,比较实用,要清楚缓存的数据格式(明确业务和缓存模型数据) @Override @CachePut(value=“cache:all”,unless=“null==#result”,key=“#root.methodName”) publicListcacheList2(){ Listall=customerRepo.findAll(); returnall; } }

4.3 扩展

基于spring缓存实现

来源:blog.csdn.net/qq_42105629/article/details/102589319

编辑:jq

未经允许不得转载:电子设备知识网 » Springboot+redis操作多种实现

分享到: 生成海报