一、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连接来完成各种操作。
二、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)
@Resource private StringRedisTemplate stringRedisTemplate; @Override public 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(); } // 缓存为空的时候,先查,然后缓存redis Optional
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 StringRedisTemplate
instance. {@link #setConnectionFactory(RedisConnectionFactory)} * and {@link #afterPropertiesSet()} still need to be called. */ public StringRedisTemplate() { RedisSerializer
<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>
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 }
新建读取配置类
@Configuration public class RedissonConfig { @Bean public 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
@RestController @RequestMapping("/") public class TeController { @Autowired private RedissonClient redissonClient; static long i = 20; static long sum = 300; // ========================== String ======================= @GetMapping("/set/{key}") public String s1(@PathVariable String key) { // 设置字符串 RBucket
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; } @Bean public CacheManager cacheManager(RedisConnectionFactory factory) { RedisSerializer
@Transactional @Service public class ReImpl implements RedisService { @Resource private CustomerRepo customerRepo; @Resource private 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
4.3 扩展
基于spring缓存实现
来源:blog.csdn.net/qq_42105629/article/details/102589319
编辑:jq
全部0条评论
快来发表一下你的评论吧 !