欢迎关注方志朋的博客,回复”666“获面试宝典

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

一、Jedis,Redisson,Lettuce三者的区别

共同点:都提供了基于Redis操作的Java API,只是封装程度,具体实现稍有不同。

不同点:

1.1、Jedis

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

特点:使用阻塞的I/O,方法调用同步,程序流需要等到socket处理完I/O才能执行,不支持异步操作。Jedis客户端实例不是线程安全的,需要通过连接池来使用Jedis。

1.2、Redisson

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

1.3、 Lettuce

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

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

二、RedisTemplate

2.1、使用配置

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

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

application-dev.yml

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

2.2、使用示例

@Resourceprivate StringRedisTemplate stringRedisTemplate;@Overridepublic CustomersEntity findById(Integer id) {// 需要缓存// 所有涉及的缓存都需要删除,或者更新try {String toString = stringRedisTemplate.opsForHash().get(REDIS_CUSTOMERS_ONE, id + "").toString();if (toString != null) {return JSONUtil.toBean(toString, CustomersEntity.class);}} catch (Exception e) {e.printStackTrace();}// 缓存为空的时候,先查,然后缓存redisOptional<CustomersEntity> byId = customerRepo.findById(id);if (byId.isPresent()) {CustomersEntity customersEntity = byId.get();try {stringRedisTemplate.opsForHash().put(REDIS_CUSTOMERS_ONE, id + "", JSONUtil.toJsonStr(customersEntity));} catch (Exception e) {e.printStackTrace();}return customersEntity;}return null;}

2.3、扩展

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

3.3.2、stringRedisTemplate API(部分展示)
  • opsForHash --> hash操作

  • opsForList --> list操作

  • opsForSet --> set操作

  • opsForValue --> string操作

  • opsForZSet --> Zset操作

3.3.3 StringRedisTemplate默认序列化机制
public class StringRedisTemplate extends RedisTemplate<String, String> {/*** Constructs a new <code>StringRedisTemplate</code> instance. {@link #setConnectionFactory(RedisConnectionFactory)}* and {@link #afterPropertiesSet()} still need to be called.*/public StringRedisTemplate() {RedisSerializer<String> stringSerializer = new StringRedisSerializer();setKeySerializer(stringSerializer);setValueSerializer(stringSerializer);setHashKeySerializer(stringSerializer);setHashValueSerializer(stringSerializer);}}

三、RedissonClient 操作示例

3.1 基本配置

3.1.1、Maven pom 引入
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency><groupId>org.redisson</groupId><artifactId>redisson</artifactId><version>3.8.2</version><optional>true</optional>
</dependency>
<dependency><groupId>org.redisson</groupId><artifactId>redisson-spring-boot-starter</artifactId><version>LATEST</version>
</dependency>
3.1.2、添加配置文件Yaml或者json格式

redisson-config.yml,Spring Boot 学习笔记分享给你看下。

# Redisson 配置
singleServerConfig:address: "redis://192.168.1.140:6379"password: nullclientName: nulldatabase: 15 #选择使用哪个数据库0~15idleConnectionTimeout: 10000pingTimeout: 1000connectTimeout: 10000timeout: 3000retryAttempts: 3retryInterval: 1500reconnectionTimeout: 3000failedAttempts: 3subscriptionsPerConnection: 5subscriptionConnectionMinimumIdleSize: 1subscriptionConnectionPoolSize: 50connectionMinimumIdleSize: 32connectionPoolSize: 64dnsMonitoringInterval: 5000#dnsMonitoring: falsethreads: 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、读取配置

新建读取配置类

Spring Boot 基础就不介绍了,推荐下这个实战教程:https://github.com/javastacks/spring-boot-best-practice

@Configuration
public class RedissonConfig {@Beanpublic RedissonClient redisson() throws IOException {// 两种读取方式,Config.fromYAML 和 Config.fromJSON
//        Config config = Config.fromJSON(RedissonConfig.class.getClassLoader().getResource("redisson-config.json"));Config config = Config.fromYAML(RedissonConfig.class.getClassLoader().getResource("redisson-config.yml"));return Redisson.create(config);}
}

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

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

3.2 使用示例

@RestController
@RequestMapping("/")
public class TeController {@Autowiredprivate RedissonClient redissonClient;static long i = 20;static long sum = 300;//    ========================== String =======================@GetMapping("/set/{key}")public String s1(@PathVariable String key) {// 设置字符串RBucket<String> keyObj = redissonClient.getBucket(key);keyObj.set(key + "1-v1");return key;}@GetMapping("/get/{key}")public String g1(@PathVariable String key) {// 设置字符串RBucket<String> keyObj = redissonClient.getBucket(key);String s = keyObj.get();return s;}//    ========================== hash =======================-=@GetMapping("/hset/{key}")public String h1(@PathVariable String key) {Ur ur = new Ur();ur.setId(MathUtil.randomLong(1,20));ur.setName(key);// 存放 HashRMap<String, Ur> ss = redissonClient.getMap("UR");ss.put(ur.getId().toString(), ur);return ur.toString();}@GetMapping("/hget/{id}")public String h2(@PathVariable String id) {// hash 查询RMap<String, Ur> ss = redissonClient.getMap("UR");Ur ur = ss.get(id);return ur.toString();}// 查询所有的 keys@GetMapping("/all")public String all(){RKeys keys = redissonClient.getKeys();Iterable<String> keys1 = keys.getKeys();keys1.forEach(System.out::println);return keys.toString();}// ================== ==============读写锁测试 =============================@GetMapping("/rw/set/{key}")public void rw_set(){
//        RedissonLock.RBucket<String> ls_count = redissonClient.getBucket("LS_COUNT");ls_count.set("300",360000000l, TimeUnit.SECONDS);}// 减法运算@GetMapping("/jf")public void jf(){String key = "S_COUNT";//        RAtomicLong atomicLong = redissonClient.getAtomicLong(key);
//        atomicLong.set(sum);
//        long l = atomicLong.decrementAndGet();
//        System.out.println(l);RAtomicLong atomicLong = redissonClient.getAtomicLong(key);if (!atomicLong.isExists()) {atomicLong.set(300l);}while (i == 0) {if (atomicLong.get() > 0) {long l = atomicLong.getAndDecrement();try {Thread.sleep(1000l);} catch (InterruptedException e) {e.printStackTrace();}i --;System.out.println(Thread.currentThread().getName() + "->" + i + "->" + l);}}}@GetMapping("/rw/get")public String rw_get(){String key = "S_COUNT";Runnable r = new Runnable() {@Overridepublic void run() {RAtomicLong atomicLong = redissonClient.getAtomicLong(key);if (!atomicLong.isExists()) {atomicLong.set(300l);}if (atomicLong.get() > 0) {long l = atomicLong.getAndDecrement();i --;System.out.println(Thread.currentThread().getName() + "->" + i + "->" + l);}}};while (i != 0) {new Thread(r).start();
//            new Thread(r).run();
//            new Thread(r).run();
//            new Thread(r).run();
//            new Thread(r).run();}RBucket<String> bucket = redissonClient.getBucket(key);String s = bucket.get();System.out.println("================线程已结束================================" + s);return s;}}

4.3 扩展

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

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

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

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

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

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

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")
public class RedisCacheConfig {private Duration timeToLive = Duration.ZERO;public void setTimeToLive(Duration timeToLive) {this.timeToLive = timeToLive;}@Beanpublic CacheManager cacheManager(RedisConnectionFactory factory) {RedisSerializer<String> redisSerializer = new StringRedisSerializer();Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);// 解决查询缓存转换异常的问题ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(om);// 配置序列化(解决乱码的问题)RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(timeToLive).serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)).disableCachingNullValues();RedisCacheManager cacheManager = RedisCacheManager.builder(factory).cacheDefaults(config).build();return cacheManager;}}

4.2 使用示例

@Transactional
@Service
public class ReImpl implements RedisService {@Resourceprivate CustomerRepo customerRepo;@Resourceprivate StringRedisTemplate stringRedisTemplate;public static final String REDIS_CUSTOMERS_ONE = "Customers";public static final String REDIS_CUSTOMERS_ALL = "allList";// =====================================================================使用Spring cahce 注解方式实现缓存// ==================================单个操作@Override@Cacheable(value = "cache:customer", unless = "null == #result",key = "#id")public CustomersEntity cacheOne(Integer id) {final Optional<CustomersEntity> byId = customerRepo.findById(id);return byId.isPresent() ? byId.get() : null;}@Override@Cacheable(value = "cache:customer", unless = "null == #result", key = "#id")public CustomersEntity cacheOne2(Integer id) {final Optional<CustomersEntity> byId = customerRepo.findById(id);return byId.isPresent() ? byId.get() : null;}// todo 自定义redis缓存的key,@Override@Cacheable(value = "cache:customer", unless = "null == #result", key = "#root.methodName + '.' + #id")public CustomersEntity cacheOne3(Integer id) {final Optional<CustomersEntity> byId = customerRepo.findById(id);return byId.isPresent() ? byId.get() : null;}// todo 这里缓存到redis,还有响应页面是String(加了很多转义符\,),不是Json格式@Override@Cacheable(value = "cache:customer", unless = "null == #result", key = "#root.methodName + '.' + #id")public String cacheOne4(Integer id) {final Optional<CustomersEntity> byId = customerRepo.findById(id);return byId.map(JSONUtil::toJsonStr).orElse(null);}// todo 缓存json,不乱码已处理好,调整序列化和反序列化@Override@Cacheable(value = "cache:customer", unless = "null == #result", key = "#root.methodName + '.' + #id")public CustomersEntity cacheOne5(Integer id) {Optional<CustomersEntity> byId = customerRepo.findById(id);return byId.filter(obj -> !StrUtil.isBlankIfStr(obj)).orElse(null);}// ==================================删除缓存@Override@CacheEvict(value = "cache:customer", key = "'cacheOne5' + '.' + #id")public Object del(Integer id) {// 删除缓存后的逻辑return null;}@Override@CacheEvict(value = "cache:customer",allEntries = true)public void del() {}@CacheEvict(value = "cache:all",allEntries = true)public void delall() {}// ==================List操作@Override@Cacheable(value = "cache:all")public List<CustomersEntity> cacheList() {List<CustomersEntity> all = customerRepo.findAll();return all;}// todo 先查询缓存,再校验是否一致,然后更新操作,比较实用,要清楚缓存的数据格式(明确业务和缓存模型数据)@Override@CachePut(value = "cache:all",unless = "null == #result",key = "#root.methodName")public List<CustomersEntity> cacheList2() {List<CustomersEntity> all = customerRepo.findAll();return all;}}

4.3 扩展

基于spring缓存实现

热门内容:
  • 如何写出让同事无法维护的代码?

  • 别再用 BeanUtils 了,这款 PO VO DTO 转换神器不香么?

  • 抖音的服务器究竟有多大?

  • 重磅消息:Spring 6 和Spring Boot 3

  • 有个程序员老公有多爽???

最近面试BAT,整理一份面试资料《Java面试BAT通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。
获取方式:点“在看”,关注公众号并回复 666 领取,更多内容陆续奉上。

明天见(。・ω・。)ノ♡

Spring Boot + Redis 实现各种操作,写得太好了吧!相关推荐

  1. 太好了 | 这篇写的太好了!Spring Boot + Redis 实现接口幂等性

    Hi ! 我是小小,今天是本周的第四篇,第四篇主要内容是 Spring Boot + Redis 实现接口幂等性 介绍 幂等性的概念是,任意多次执行所产生的影响都与一次执行产生的影响相同,按照这个含义 ...

  2. Spring Boot Redis Cluster 实战干货

    转载自  Spring Boot Redis Cluster 实战干货 添加配置信息 spring.redis:database: 0 # Redis数据库索引(默认为0)#host: 192.168 ...

  3. Spring Boot Redis缓存

    Spring Boot Redis缓存 目录[ 隐藏 ] 1 Spring Boot Redis缓存 1.1 Spring Boot Redis项目设置 1.2 Spring Boot Redis缓存 ...

  4. java+cache使用方法_java相关:Spring boot redis cache的key的使用方法

    java相关:Spring boot redis cache的key的使用方法 发布于 2020-8-16| 复制链接 摘记: 在数据库查询中我们往往会使用增加缓存来提高程序的性能,@Cacheabl ...

  5. Spring Boot + JPA +MySQL 数据操作及示例环境搭建(自动建表)

    JPA 是Java官方提供的数据持久的统一API , 是一个接口标准,并没有具体实现. JPA的实现常见的有: Hibernate TopLink (Eclipse Link) Spring Boot ...

  6. Spring Boot Redis关闭

    Spring Boot Redis 在开发或者本地没有redis数据库时,控制台会一直报连接超时的日志,可以通过配置取消: spring: data:redis:repositories:enable ...

  7. Spring Boot之jdbc数据操作06

    Spring Boot之jdbc数据操作06 JDBC 通过快速创建spring boot项目选择 mysql 和jdbc 创建一个基于web的spring boot项目 依赖为 <depend ...

  8. Spring Boot + Redis 操作多种实现

    欢迎关注方志朋的博客,回复"666"获面试宝典 一.Jedis,Redisson,Lettuce三者的区别 共同点:都提供了基于Redis操作的Java API,只是封装程度,具体 ...

  9. 手把手教你写一个获取短信验证码业务(基于Spring Boot+Redis+阿里云短信服务)

    文章目录 一.阿里云短信环境搭建 1.开启使用子用户,创建用户组和用户 2.开通阿里云短信服务 二.环境测试 1.新建Spring Boot(web)项目,导入依赖 2.在测试类中进行测试 三.真实业 ...

最新文章

  1. 360金融首席科学家张家兴:只靠AI Lab做不好AI中台 | 独家专访
  2. 图灵科普系列丛书封面有奖征集(贴图送书)
  3. react fiber_让我们爱上React Fiber
  4. ROS官网新手级教程总结
  5. linux桌面xfce美化_Xfce Linux桌面环境,Arduino机器人,热门DevOps书籍,FreeDOS,Python,Go等
  6. 计算机的doc命令怎么学,如何进入dos系统 四种方法教学【图文教程】
  7. vue仿网易云音乐播放器界面
  8. css单线边框_css中的border-collapse属性如何设置表格边框线?(代码示例)
  9. Coursera machine learning week 6 excise
  10. 520,让爱的传递永不停歇
  11. python打开paint并画一个圆
  12. 路由控制——ACL、IP-Prefix List
  13. 加速度计与陀螺仪区别
  14. JavaScript 数字格式化怎么写(#,##.00) (实用,赞)
  15. 冷冻大脑、量产蟋蟀...全球最聪明的人一起开脑洞是什么样?
  16. 【JavaScript】DOM笔记(随缘更新ing)
  17. 太原网络营销师揭秘每个老板最头疼的百度竞价(SEM)如何提供转化率?
  18. 点云库PCL学习笔记 -- 点云滤波Filtering -- 3. StatisticalOutlierRemoval 统计滤波器
  19. JS(javascript) 将网站加入收藏夹
  20. 数的机器码表示(原码,反码,补码,移码)

热门文章

  1. 2018-3-11 HDFS2.X
  2. CentOS 7 添加系统开机服务
  3. JavaScript-也来谈--闭包
  4. [Python]网络打解包
  5. [Android]webview直接加载网页允许JS,进度条,当前应用内跳转
  6. hdu1518 bjfuoj1042 zoj1909 poj2362 经典的搜索加剪枝
  7. HDU3434数学题
  8. NHibernate之旅(11):探索多对多关系及其关联查询
  9. 突然想起99年的那次离别
  10. 【组队学习】【28期】基于transformers的自然语言处理(NLP)入门