赞
踩
Jedis、Lettuce、RedisTemplate和Redisson都是用于与Redis进行交互的Java客户端库。区别如下:
特点 | Jedis | Lettuce | RedisTemplate | Redisson |
---|---|---|---|---|
同步/异步 | 同步 | 异步 | 同步 | 异步 |
阻塞/非阻塞 | 阻塞 | 非阻塞 | 阻塞 | 非阻塞 |
性能 | 适用于单线程 | 适用于高并发环境 | 适用于单线程 | 适用于高并发环境 |
Spring集成 | 不是Spring项目的一部分 | 不是Spring项目的一部分 | Spring Data Redis的一部分 | 不是Spring项目的一部分 |
易用性 | 基本的Redis操作 | 异步操作和响应式编程 | 更高级的抽象,对象映射 | 高级分布式功能,易于使用 |
分布式功能 | 有限支持 | 有限支持 | 有限支持 | 强大的分布式功能 |
redisTemplate中的RedisConnectionFactory基于jedis和lettuce实现的,springboot2.7.3中默认就是lettuce实现。
字不多写,现在开始整合jedis。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <exclusions> <!-- 排除lettuce --> <exclusion> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </exclusion> </exclusions> </dependency> <!-- 不用写版本号,2.7.3中自带版本号 --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency>
网上比较多的教程需要配置jedis,实际上大可不必,springboot都有默认的参数,使用默认参数即可
spring:
redis:
host: 127.0.0.1
port: 6379
password: 123456789
database: 0
timeout: 20000
connect-timeout: 20000
配置相关的属性和工厂
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.data.redis.RedisProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisPassword; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; /** * 整合jedis * * @author milu * @date 2023/9/6 */ @Slf4j @Configuration public class RedisForJedisConfig { @Autowired private RedisProperties redisProperties; @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); om.disable(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS); om.registerModule(new JavaTimeModule()); jackson2JsonRedisSerializer.setObjectMapper(om); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); redisTemplate.setKeySerializer(stringRedisSerializer); redisTemplate.setHashKeySerializer(stringRedisSerializer); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } @Bean public RedisConnectionFactory factory(JedisPoolConfig jedisPoolConfig, RedisStandaloneConfiguration redisStandaloneConfiguration) { JedisConnectionFactory connectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration); connectionFactory.setPoolConfig(jedisPoolConfig); return connectionFactory; } @Bean public RedisStandaloneConfiguration redisStandaloneConfiguration() { RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(); config.setHostName(redisProperties.getHost()); config.setPort(redisProperties.getPort()); config.setDatabase(redisProperties.getDatabase()); config.setPassword(RedisPassword.of(redisProperties.getPassword())); return config; } @Bean public JedisPoolConfig jedisPoolConfig() { RedisProperties.Pool pool = redisProperties.getJedis().getPool(); JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(pool.getMaxActive()); jedisPoolConfig.setMaxIdle(pool.getMaxIdle()); jedisPoolConfig.setMinIdle(pool.getMinIdle()); jedisPoolConfig.setMaxWait(pool.getMaxWait()); return jedisPoolConfig; } @Bean public JedisPool jedisPool(JedisPoolConfig jedisPoolConfig) { return new JedisPool(jedisPoolConfig, redisProperties.getHost(), redisProperties.getPort(), 0, redisProperties.getPassword(), redisProperties.getDatabase()); } }
启动项目,查看redisTemplate的connectionFacrory是否变成JedisConnectionFactory。
整合完成。最后附加两个工具类。大家自行取用即可。
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** * redis组件 * * @author mi lu * @date 2023/9/6 */ @Component public class RedisComponent { @Autowired private RedisTemplate<String, Object> redisTemplate; // =============================common============================ /** * 指定缓存失效时间 * * @param key 键 * @param time 时间(秒) * @return */ public boolean expire(String key, long time) { try { if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根据key 获取过期时间 * * @param key 键 不能为null * @return 时间(秒) 返回0代表为永久有效 */ public long getExpire(String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * 判断key是否存在 * * @param key 键 * @return true 存在 false不存在 */ public boolean hasKey(String key) { try { return redisTemplate.hasKey(key); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 删除缓存 * * @param key 可以传一个值 或多个 */ @SuppressWarnings("unchecked") public void del(String... key) { if (key != null && key.length > 0) { if (key.length == 1) { redisTemplate.delete(key[0]); } else { redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key)); } } } // ============================String============================= /** * 普通缓存获取 * * @param key 键 * @return 值 */ public Object get(String key) { return key == null ? null : redisTemplate.opsForValue().get(key); } /** * 普通缓存放入 * * @param key 键 * @param value 值 * @return true成功 false失败 */ public boolean set(String key, Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 普通缓存放入并设置时间 * * @param key 键 * @param value 值 * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 * @return true成功 false 失败 */ public boolean set(String key, Object value, long time) { try { if (time > 0) { redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); } else { set(key, value); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 递增 * * @param key 键 * @param delta 要增加几(大于0) * @return */ public long incr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递增因子必须大于0"); } return redisTemplate.opsForValue().increment(key, delta); } /** * 递减 * * @param key 键 * @param delta 要减少几(小于0) * @return */ public long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递减因子必须大于0"); } return redisTemplate.opsForValue().increment(key, -delta); } // ================================Map================================= /** * HashGet * * @param key 键 不能为null * @param item 项 不能为null * @return 值 */ public Object hget(String key, String item) { return redisTemplate.opsForHash().get(key, item); } /** * 获取hashKey对应的所有键值 * * @param key 键 * @return 对应的多个键值 */ public Map<Object, Object> hmget(String key) { return redisTemplate.opsForHash().entries(key); } /** * HashSet * * @param key 键 * @param map 对应多个键值 * @return true 成功 false 失败 */ public boolean hmset(String key, Map<String, Object> map) { try { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * HashSet 并设置时间 * * @param key 键 * @param map 对应多个键值 * @param time 时间(秒) * @return true成功 false失败 */ public boolean hmset(String key, Map<String, Object> map, long time) { try { redisTemplate.opsForHash().putAll(key, map); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 向一张hash表中放入数据,如果不存在将创建 * * @param key 键 * @param item 项 * @param value 值 * @return true 成功 false失败 */ public boolean hset(String key, String item, Object value) { try { redisTemplate.opsForHash().put(key, item, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 向一张hash表中放入数据,如果不存在将创建 * * @param key 键 * @param item 项 * @param value 值 * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间 * @return true 成功 false失败 */ public boolean hset(String key, String item, Object value, long time) { try { redisTemplate.opsForHash().put(key, item, value); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 删除hash表中的值 * * @param key 键 不能为null * @param item 项 可以使多个 不能为null */ public void hdel(String key, Object... item) { redisTemplate.opsForHash().delete(key, item); } /** * 判断hash表中是否有该项的值 * * @param key 键 不能为null * @param item 项 不能为null * @return true 存在 false不存在 */ public boolean hHasKey(String key, String item) { return redisTemplate.opsForHash().hasKey(key, item); } /** * hash递增 如果不存在,就会创建一个 并把新增后的值返回 * * @param key 键 * @param item 项 * @param by 要增加几(大于0) * @return */ public double hincr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, by); } /** * hash递减 * * @param key 键 * @param item 项 * @param by 要减少记(小于0) * @return */ public double hdecr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, -by); } // ============================set============================= /** * 根据key获取Set中的所有值 * * @param key 键 * @return */ public Set<Object> sGet(String key) { try { return redisTemplate.opsForSet().members(key); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 根据value从一个set中查询,是否存在 * * @param key 键 * @param value 值 * @return true 存在 false不存在 */ public boolean sHasKey(String key, Object value) { try { return redisTemplate.opsForSet().isMember(key, value); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将数据放入set缓存 * * @param key 键 * @param values 值 可以是多个 * @return 成功个数 */ public long sSet(String key, Object... values) { try { return redisTemplate.opsForSet().add(key, values); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 将set数据放入缓存 * * @param key 键 * @param time 时间(秒) * @param values 值 可以是多个 * @return 成功个数 */ public long sSetAndTime(String key, long time, Object... values) { try { Long count = redisTemplate.opsForSet().add(key, values); if (time > 0) expire(key, time); return count; } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 获取set缓存的长度 * * @param key 键 * @return */ public long sGetSetSize(String key) { try { return redisTemplate.opsForSet().size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 移除值为value的 * * @param key 键 * @param values 值 可以是多个 * @return 移除的个数 */ public long setRemove(String key, Object... values) { try { Long count = redisTemplate.opsForSet().remove(key, values); return count; } catch (Exception e) { e.printStackTrace(); return 0; } } // ===============================list================================= /** * 获取list缓存的内容 * * @param key 键 * @param start 开始 * @param end 结束 0 到 -1代表所有值 * @return */ public List<Object> lGet(String key, long start, long end) { try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 获取list缓存的长度 * * @param key 键 * @return */ public long lGetListSize(String key) { try { return redisTemplate.opsForList().size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 通过索引 获取list中的值 * * @param key 键 * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推 * @return */ public Object lGetIndex(String key, long index) { try { return redisTemplate.opsForList().index(key, index); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @return */ public boolean lSet(String key, Object value) { try { redisTemplate.opsForList().rightPush(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @param time 时间(秒) * @return */ public boolean lSet(String key, Object value, long time) { try { redisTemplate.opsForList().rightPush(key, value); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @return */ public boolean lSet(String key, List<Object> value) { try { redisTemplate.opsForList().rightPushAll(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @param time 时间(秒) * @return */ public boolean lSet(String key, List<Object> value, long time) { try { redisTemplate.opsForList().rightPushAll(key, value); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根据索引修改list中的某条数据 * * @param key 键 * @param index 索引 * @param value 值 * @return */ public boolean lUpdateIndex(String key, long index, Object value) { try { redisTemplate.opsForList().set(key, index, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 移除N个值为value * * @param key 键 * @param count 移除多少个 * @param value 值 * @return 移除的个数 */ public long lRemove(String key, long count, Object value) { try { Long remove = redisTemplate.opsForList().remove(key, count, value); return remove; } catch (Exception e) { e.printStackTrace(); return 0; } } }
package com.monitor.system.component; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.Transaction; import redis.clients.jedis.Tuple; import redis.clients.jedis.params.SetParams; import java.util.*; import java.util.function.Consumer; import java.util.function.Function; /** * jedisPool组件 * * @author mi lu * @date 2023/9/6 */ @Slf4j @Component public class JedisPoolComponent { public static final SetParams setParams = new SetParams(); private static final String LOCK_SUCCESS = "OK"; private static final String UNLOCK_LUA = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; private static final Long RELEASE_SUCCESS = 1L; private static final Long retryMill = (long) 1000 * 1000; @Autowired private JedisPool jedisPool; /** * 获取分布式锁 * * @param lockKey * @param requestId * @param expireTime 毫秒 */ public Boolean tryDistributedLock(String lockKey, String requestId, int expireTime) { log.info("tryGetDistributedLock-->>lockKey = {}, requestId = {}, expireTime = {}", lockKey, requestId, expireTime); String result = this.lock(lockKey, requestId, expireTime); log.info("tryGetDistributedLock-->>lockKey = {}, requestId = {}, result = {}", lockKey, requestId, result); return LOCK_SUCCESS.equals(result); } /** * @param lockKey 上锁的key * @param expireTime 锁的超时时间 * @param retryTimeNano 最多尝试多久 纳秒单位 * @return * @throws InterruptedException */ public String lock(String lockKey, int expireTime, long retryTimeNano) { int rt = 0; String key = null; try { while (true) { key = String.valueOf(System.nanoTime()); String result = this.lock(lockKey, key, expireTime); if (LOCK_SUCCESS.equals(result)) { return key; } // 获取锁失败 rt += retryMill;//每隔1 ms执行一次 if (rt <= retryTimeNano) { // 下次可以执行 Thread.sleep(retryMill); } else { return null; } } } catch (InterruptedException e) { return null; } } /** * 释放分布式锁 * * @param lockKey 锁 * @param requestId 请求标识 * @return 是否释放成功 */ public boolean releaseDistributedLock(String lockKey, String requestId) { log.info("releaseDistributedLock-->>, lockKey = {}, requestId = {}", lockKey, requestId); Object result = this.eval(UNLOCK_LUA, Collections.singletonList(lockKey), Collections.singletonList(requestId)); log.info("releaseDistributedLock, lockKey = {}, requestId = {}, result = {}", lockKey, requestId, result); if (RELEASE_SUCCESS.equals(result)) { log.info("releaselock>>>>>>>>>>>>>>>> lockKey = {}, requestId = {}", lockKey, requestId); return true; } log.info("锁已释放, lockKey = {}, requestId = {}", lockKey, requestId); return false; } public final <OUT> OUT redisExec(Function<Jedis, OUT> function) { Jedis jedis = null; try { jedis = jedisPool.getResource(); return function.apply(jedis); } catch (Exception e) { log.info("redisExec error, errorMsg = {}", e.getMessage()); throw e; } finally { Optional.ofNullable(jedis).ifPresent(j -> j.close()); } } public String lock(final String key, final String value, final int time) { return redisExec(jedis -> jedis.set(key, value, setParams.nx().px(time))); } public Object eval(String script, List<String> keys, List<String> args) { return redisExec(jedis -> jedis.eval(script, keys, args)); } public String get(String key) { return this.redisExec(redis -> redis.get(key)); } public byte[] getBytes(byte[] key) { return this.redisExec(redis -> redis.get(key)); } public void set(String key, String val) { this.redisExec(redis -> redis.set(key, val)); } public Long incr(String key) { return this.redisExec(redis -> redis.incr(key)); } public Long append(String key, String value) { return this.redisExec(redis -> redis.append(key, value)); } public void set(String key, String val, long expireSecond) { this.redisTxExec(tx -> { tx.set(key, val); tx.expire(key, expireSecond); }); } public Long rpush(String key, String val) { return this.redisExec(tx -> tx.rpush(key, val)); } public String lpop(String key) { return this.redisExec(tx -> tx.lpop(key)); } public void setBytes(byte[] key, byte[] val, int expireSecond) { this.redisTxExec(tx -> { tx.set(key, val); tx.expire(key, expireSecond); }); } public Long SAdd(String key, final String... field) { return this.redisExec((redis -> redis.sadd(key, field))); } public Long ZAdd(String key, double score, String mem) { return this.redisExec((redis -> redis.zadd(key, score, mem))); } public Long SRem(String key, final String... field) { return this.redisExec((redis -> redis.srem(key, field))); } public Long IncBy(String key, Long val) { return this.redisExec((redis -> redis.incrBy(key, val))); } public Long del(String key) { return this.redisExec(redis -> redis.del(key)); } public Long del(byte[] key) { return this.redisExec(redis -> redis.del(key)); } public Long delByte(byte[] key) { return this.redisExec(redis -> redis.del(key)); } public Long hdel(String key, String fileds) { return this.redisExec(redis -> redis.hdel(key, fileds)); } public Boolean exists(String key) { return this.redisExec(redis -> redis.exists(key)); } public Long scard(String key) { return this.redisExec(redis -> redis.scard(key)); } public String srandmember(String key) { return this.redisExec(redis -> redis.srandmember(key)); } public Set<String> smembers(String key) { return this.redisExec(redis -> redis.smembers(key)); } public boolean sismember(String key, String value) { return this.redisExec(redis -> redis.sismember(key, value)); } public Boolean hexists(String key, String ele) { return this.redisExec(redis -> redis.hexists(key, ele)); } public String hget(String key, String filed) { return this.redisExec(redis -> redis.hget(key, filed)); } public Map<String, String> hgetall(String key) { return redisExec(redis -> redis.hgetAll(key)); } public Set<String> zrange(String key, Long start, Long end) { return this.redisExec(redis -> redis.zrange(key, start, end)); } public Long zadd(String key, double score, String member) { return this.redisExec(redis -> redis.zadd(key, score, member)); } public Long zrem(String key, String... mem) { return this.redisExec(r -> r.zrem(key, mem)); } public Set<String> zrevrange(String key, Long start, Long end) { return this.redisExec(redis -> redis.zrevrange(key, start, end)); } public Set<Tuple> zrevrangeWithScores(String key, Long start, Long end) { return this.redisExec(redis -> redis.zrevrangeWithScores(key, start, end)); } public Set<Tuple> zrangeWithScores(String key, Long start, Long end) { return this.redisExec(redis -> redis.zrangeWithScores(key, start, end)); } public Long zrank(String key, String member) { return this.redisExec(redis -> redis.zrank(key, member)); } public Set<String> hkeys(String key) { return this.redisExec(redis -> redis.hkeys(key)); } public List<String> lrange(String key, Long start, Long end) { return this.redisExec(redis -> redis.lrange(key, start, end)); } public Long expire(String key, int expireSecond) { return this.redisExec(redis -> redis.expire(key, expireSecond)); } public Long TTL(String key) { return this.redisExec(redis -> redis.ttl(key)); } public void redisTxExec(Consumer<Transaction> consumer) { List<Object> result = this.redisExec(jedis -> { Transaction tx = jedis.multi(); consumer.accept(tx); return tx.exec(); }); } public void redisWatchTxExec(Consumer<Transaction> consumer, String... args) { Jedis jedis = null; try { jedis = jedisPool.getResource(); jedis.watch(args); Transaction tx = jedis.multi(); consumer.accept(tx); List<Object> execResult = tx.exec(); log.info("jedis tx result = {}", execResult); if (CollectionUtils.isEmpty(execResult)) { return; } } catch (Exception e) { e.printStackTrace(); log.info("redisExec error, errorMsg = {}", e.getMessage()); throw e; } finally { Optional.ofNullable(jedis).ifPresent(j -> j.close()); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。