springboot项目中使用redis缓存

编程

导入redis jar包

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

application.properties redis配置项

spring.cache.type=redis

spring.redis.host=127.0.0.1

spring.redis.port=6379

spring.redis.database=0

spring.redis.password=111111

spring.redis.timeout=0

spring.redis.ssl=false

spring.redis.jedis.pool.max-active=300

spring.redis.jedis.pool.max-wait=-1

spring.redis.jedis.pool.max-idle=300

spring.redis.jedis.pool.min-idle=1

redis配置类

@Configuration

@EnableCaching

public class RedisCacheConfig extends CachingConfigurerSupport {

@Autowired

private RedisProperties redisProperties;

@Autowired

private RedisProperties.Pool redisPropertiesPool;

@Bean

@ConditionalOnMissingBean(name = "poolConfig")

public JedisPoolConfig poolConfig() {

JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();

jedisPoolConfig.setBlockWhenExhausted(true);

jedisPoolConfig.setTestOnBorrow(true);

jedisPoolConfig.setMaxTotal(redisPropertiesPool.getMaxActive());

jedisPoolConfig.setMaxIdle(redisPropertiesPool.getMaxIdle());

jedisPoolConfig.setMinIdle(redisPropertiesPool.getMinIdle());

jedisPoolConfig.setMaxWaitMillis(redisPropertiesPool.getMaxWait());// 100000

jedisPoolConfig.setTestOnBorrow(true);

jedisPoolConfig.setTestOnReturn(true);

//Idle时进行连接扫描

jedisPoolConfig.setTestWhileIdle(true);

//表示idle object evitor两次扫描之间要sleep的毫秒数

jedisPoolConfig.setTimeBetweenEvictionRunsMillis(30000);

//表示idle object evitor每次扫描的最多的对象数

jedisPoolConfig.setNumTestsPerEvictionRun(10);

//表示一个对象至少停留在idle状态的最短时间,然后才能被idle object evitor扫描并驱逐;这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义

jedisPoolConfig.setMinEvictableIdleTimeMillis(60000);

return jedisPoolConfig;

}

@Bean

@ConditionalOnMissingBean(name = "jedisPool")

public JedisPool jedisPool(JedisPoolConfig poolConfig) {

return new JedisPool(poolConfig,

redisProperties.getHost(),

redisProperties.getPort(),

redisProperties.getTimeout().getNano(),

redisProperties.getPassword());

}

@Bean

@ConditionalOnMissingBean(name = "redisConnectionFactory")

public RedisConnectionFactory redisConnectionFactory(JedisPoolConfig poolConfig) {

RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();

//设置redis服务器的host或者ip地址

redisStandaloneConfiguration.setHostName(redisProperties.getHost());

redisStandaloneConfiguration.setPort(redisProperties.getPort());

redisStandaloneConfiguration.setPassword(redisProperties.getPassword());

redisStandaloneConfiguration.setDatabase(redisProperties.getDatabase());

//获得默认的连接池构造

//这里需要注意的是,edisConnectionFactoryJ对于Standalone模式的没有(RedisStandaloneConfiguration,JedisPoolConfig)的构造函数,对此

//我们用JedisClientConfiguration接口的builder方法实例化一个构造器,还得类型转换

JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcf = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration.builder();

//修改我们的连接池配置

jpcf.poolConfig(poolConfig);

//通过构造器来构造jedis客户端配置

JedisClientConfiguration jedisClientConfiguration = jpcf.build();

return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);

}

@Primary

@Bean

public CacheManager cacheManager(@Qualifier("redisConnectionFactory") RedisConnectionFactory redisConnectionFactory) {

RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();

//.entryTtl(Duration.ofHours(1)) // 设置缓存有效期一小时

//.disableCachingNullValues(); // 不缓存空值

return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))

.cacheDefaults(redisCacheConfiguration).build();

}

/**

* 实例化 RedisTemplate 对象

*

* @return

*/

@Bean(name = "redisTemplate")

@ConditionalOnMissingBean(name = "redisTemplate")

public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

RedisTemplate<String, Object> template = new RedisTemplate<>();

template.setConnectionFactory(redisConnectionFactory);

RedisSerializer<String> redisSerializer = new StringRedisSerializer();

Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = this.jackson2JsonRedisSerializer();

template.setKeySerializer(redisSerializer);

template.setValueSerializer(jackson2JsonRedisSerializer);

template.setHashKeySerializer(redisSerializer);

template.setHashValueSerializer(jackson2JsonRedisSerializer);

template.afterPropertiesSet();

return template;

}

@Bean(name = "stringRedisTemplate")

@ConditionalOnMissingBean(name = "stringRedisTemplate")

public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {

StringRedisTemplate template = new StringRedisTemplate();

template.setConnectionFactory(redisConnectionFactory);

RedisSerializer<String> redisSerializer = new StringRedisSerializer();

Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = this.jackson2JsonRedisSerializer();

template.setKeySerializer(redisSerializer);

template.setValueSerializer(jackson2JsonRedisSerializer);

template.setHashKeySerializer(redisSerializer);

template.setHashValueSerializer(jackson2JsonRedisSerializer);

template.afterPropertiesSet();

return template;

}

private Jackson2JsonRedisSerializer jackson2JsonRedisSerializer() {

ObjectMapper om = new ObjectMapper();

om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

jackson2JsonRedisSerializer.setObjectMapper(om);

return jackson2JsonRedisSerializer;

}

/**

* 对hash类型的数据操作

*

* @param redisTemplate

* @return

*/

@Bean

public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {

return redisTemplate.opsForHash();

}

/**

* 对redis字符串类型数据操作

*

* @param redisTemplate

* @return

*/

@Bean

public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {

return redisTemplate.opsForValue();

}

/**

* 对链表类型的数据操作

*

* @param redisTemplate

* @return

*/

@Bean

public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {

return redisTemplate.opsForList();

}

/**

* 对无序集合类型的数据操作

*

* @param redisTemplate

* @return

*/

@Bean

public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {

return redisTemplate.opsForSet();

}

/**

* 对有序集合类型的数据操作

*

* @param redisTemplate

* @return

*/

@Bean

public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {

return redisTemplate.opsForZSet();

}

@Bean

@Override

public KeyGenerator keyGenerator() {

return new KeyGenerator() {

@Override

public Object generate(Object target, Method method, Object... params) {

StringBuilder sb = new StringBuilder();

sb.append(target.getClass().getName());

sb.append(method.getName());

for (Object obj : params) {

sb.append(obj.toString());

}

return sb.toString();

}

};

}

@Bean

public RedisLockRegistry redisLockRegistry(@Qualifier("redisConnectionFactory") RedisConnectionFactory redisConnectionFactory) {

return new RedisLockRegistry(redisConnectionFactory, "redis_locks", 6000L);

}

@Bean

public Jedis jedis(@Qualifier("jedisPool") JedisPool jedisPool) {

return jedisPool.getResource();

}

@Bean

@ConditionalOnMissingBean(name = "redisUtils")

public RedisUtils redisUtils() {

return new RedisUtils();

}

}

redis工具类

@Component

@Slf4j

public class RedisUtils {

private static final Charset REDIS_CODE = Charset.forName("UTF-8");

@Autowired

private RedisTemplate<String, Object> redisTemplate;

@Autowired

private StringRedisTemplate stringRedisTemplate;

public boolean hasKey(String key) {

return (boolean) redisTemplate.execute(new RedisCallback<Boolean>() {

@Override

public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {

return redisConnection.exists(key.getBytes());

}

});

}

public void delete(String key) {

redisTemplate.delete(key);

}

/**

* 删除缓存

*

* @param key 可以传一个值 或多个

*/

@SuppressWarnings("unchecked")

public void del(String... key) {

if (key != null && key.length > 0) {

if (key.length == 1) {

stringRedisTemplate.delete(key[0]);

//redisTemplate.getConnectionFactory().getConnection().del(key[0].getBytes());

} else {

stringRedisTemplate.delete(CollectionUtils.arrayToList(key));

}

}

}

public void set(String key, String value) {

ValueOperations valueOperations = redisTemplate.opsForValue();

valueOperations.set(key, value);

}

public void set(String key, String value, final long expireTime, TimeUnit timeUnit) {

ValueOperations valueOperations = redisTemplate.opsForValue();

valueOperations.set(key, value, expireTime, timeUnit);

}

public void set(String key, final String value, final long expireTime) {

redisTemplate.execute((RedisCallback) redisConnection -> {

redisConnection.set(key.getBytes(), value.getBytes(), Expiration.seconds(expireTime), RedisStringCommands.SetOption.upsert());

return null;

});

}

public Optional<String> get(String key) {

String result = (String) redisTemplate.execute((RedisCallback) redisConnection -> {

String result1 = null;

try {

result1 = new String(redisConnection.get(key.getBytes()));

} catch (Exception e) {

return null;

}

return result1;

});

return result == null ? Optional.empty() : Optional.of(result.toString());

}

public void setStr(String key, String value) {

stringRedisTemplate.opsForValue().set(key, value);

}

public String getStr(String key) {

if (StringUtils.isBlank(key)) {

return null;

}

String value = stringRedisTemplate.opsForValue().get(key);

return value;

}

public void hashSet(String key, String field, String value) {

HashOperations hashOperations = redisTemplate.opsForHash();

hashOperations.put(key, field, value);

}

public Optional<String> hashGet(String key, String field) {

HashOperations hashOperations = redisTemplate.opsForHash();

Object result = hashOperations.get(key, field);

return result == null ? Optional.empty() : Optional.of(result.toString());

}

/**

* HashSet

*

* @param key 键

* @param map 对应多个键值

* @return true 成功 false 失败

*/

public boolean hmset(String key, HashMap<String, Object> map) {

try {

stringRedisTemplate.opsForHash().putAll(key, map);

return true;

} catch (Exception e) {

log.error("hmset error", e);

return false;

}

}

/**

* HashGet

*

* @param key 键 不能为null

* @param item 项 不能为null

* @return 值

*/

public Object hget(String key, String item) {

return stringRedisTemplate.opsForHash().get(key, item);

}

/**

* 获取hashKey对应的所有键值

*

* @param key 键

* @return 对应的多个键值

*/

public Map<Object, Object> hmget(String key) {

Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(key);

return map;

}

/**

* 向一张hash表中放入数据,如果不存在将创建

*

* @param key 键

* @param item 项

* @param value 值

* @return true 成功 false失败

*/

public boolean hset(String key, String item, Object value) {

try {

stringRedisTemplate.opsForHash().put(key, item, value);

return true;

} catch (Exception e) {

log.error("hset error", e);

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 {

stringRedisTemplate.opsForHash().put(key, item, value);

if (time > 0) {

expire(key, time);

}

return true;

} catch (Exception e) {

log.error("hset error", e);

return false;

}

}

/**

* 删除hash表中的值

*

* @param key 键 不能为null

* @param item 项 可以使多个 不能为null

*/

public void hdel(String key, Object... item) {

stringRedisTemplate.opsForHash().delete(key, item);

}

/**

* 判断hash表中是否有该项的值

*

* @param key 键 不能为null

* @param item 项 不能为null

* @return true 存在 false不存在

*/

public boolean hHasKey(String key, String item) {

return stringRedisTemplate.opsForHash().hasKey(key, item);

}

/**

* hash递增 如果不存在,就会创建一个 并把新增后的值返回

*

* @param key 键

* @param item 项

* @param by 要增加几(大于0)

* @return

*/

public double hincr(String key, String item, double by) {

return stringRedisTemplate.opsForHash().increment(key, item, by);

}

/**

* hash递减

*

* @param key 键

* @param item 项

* @param by 要减少记(小于0)

* @return

*/

public double hdecr(String key, String item, double by) {

return stringRedisTemplate.opsForHash().increment(key, item, -by);

}

/**

* 指定缓存失效时间

*

* @param key 键

* @param time 时间(秒)

* @return

*/

public boolean expire(String key, long time) {

try {

if (time > 0) {

stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);

redisTemplate.expire(key, time, TimeUnit.SECONDS);

}

return true;

} catch (Exception e) {

log.error("expire error", e);

return false;

}

}

/**

* 根据key 获取过期时间

*

* @param key 键 不能为null

* @return 时间(秒) 返回0代表为永久有效

*/

public long getExpire(String key) {

return stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);

}

//============================set=============================

/**

* 根据key获取Set中的所有值

*

* @param key 键

* @return

*/

public Set<String> sGet(String key) {

try {

return stringRedisTemplate.opsForSet().members(key);

} catch (Exception e) {

log.error("sGet error", e);

return null;

}

}

/**

* 根据value从一个set中查询,是否存在

*

* @param key 键

* @param value 值

* @return true 存在 false不存在

*/

public boolean sHasKey(String key, Object value) {

try {

return stringRedisTemplate.opsForSet().isMember(key, value);

} catch (Exception e) {

log.error("sHasKey error", e);

return false;

}

}

//===============================list=================================

/**

* 将list放入缓存

*

* @param key 键

* @param value 值

* @return

*/

public boolean lSet(String key, String value) {

try {

stringRedisTemplate.opsForList().rightPush(key, value);

return true;

} catch (Exception e) {

log.error("lSet error", e);

return false;

}

}

/**

* 将list放入缓存

*

* @param key 键

* @param value 值

* @param time 时间(秒)

* @return

*/

public boolean lSet(String key, String value, long time) {

try {

stringRedisTemplate.opsForList().rightPush(key, value);

if (time > 0) {

expire(key, time);

}

return true;

} catch (Exception e) {

log.error("lSet error", e);

return false;

}

}

/**

* 将list放入缓存

*

* @param key 键

* @param value 值

* @return

*/

/*public boolean lSet(String key, List<String> value) {

try {

stringRedisTemplate.opsForList().rightPushAll(key, value);

return true;

} catch (Exception e) {

log.error("lSet error", e);

return false;

}

}*/

public boolean lSet(String key, List<Object> value) {

try {

redisTemplate.opsForList().rightPushAll(key, value);

return true;

} catch (Exception e) {

log.error("lSet error", e);

return false;

}

}

public boolean publish(String channel, JSONObject value) {

try {

redisTemplate.convertAndSend(channel, value);

//stringRedisTemplate.convertAndSend(channel,value);

return true;

} catch (Exception e) {

log.error("publish error", e);

return false;

}

}

public boolean publishMsg(String channel, String value) {

try {

redisTemplate.convertAndSend(channel, value);

//stringRedisTemplate.convertAndSend(channel,value);

return true;

} catch (Exception e) {

log.error("publishMsg error", e);

return false;

}

}

public boolean lpush(String key, JSONObject value) {

try {

//jedis.lpush(key, value.toString());

redisTemplate.opsForList().leftPush(key, value.toString());

return true;

} catch (Exception e) {

log.error("lpush error", e);

return false;

}

}

public boolean lpush(String key, String value) {

try {

//jedis.lpush(key, value.toString());

redisTemplate.opsForList().leftPush(key, value);

return true;

} catch (Exception e) {

log.error("lpush error", e);

return false;

}

}

public Object lpop(String key) {

try {

Object object = redisTemplate.opsForList().leftPop(key);

return object;

} catch (Exception e) {

log.error("lpop error", e);

}

return null;

}

public Object rpop(String key) {

try {

Object object = redisTemplate.opsForList().rightPop(key);

return object;

} catch (Exception e) {

log.error("rpop error", e);

}

return null;

}

/**

* 将list放入缓存

*

* @param key 键

* @param value 值

* @param time 时间(秒)

* @return

*/

public boolean lSet(String key, List<String> value, long time) {

try {

stringRedisTemplate.opsForList().rightPushAll(key, value);

if (time > 0) {

expire(key, time);

}

return true;

} catch (Exception e) {

log.error("lSet error", e);

return false;

}

}

/**

* 获取list缓存的内容

*

* @param key 键

* @param start 开始

* @param end 结束 0 到 -1代表所有值

* @return

*/

public List<String> lGet(String key, long start, long end) {

try {

return stringRedisTemplate.opsForList().range(key, start, end);

} catch (Exception e) {

log.error("lGet error", e);

return null;

}

}

/**

* 获取list缓存的长度

*

* @param key 键

* @return

*/

public long lGetListSize(String key) {

try {

return stringRedisTemplate.opsForList().size(key);

} catch (Exception e) {

log.error("lGetListSize error", e);

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 stringRedisTemplate.opsForList().index(key, index);

} catch (Exception e) {

log.error("lGetIndex error", e);

return null;

}

}

/**

* 根据索引修改list中的某条数据

*

* @param key 键

* @param index 索引

* @param value 值

* @return

*/

public boolean lUpdateIndex(String key, long index, String value) {

try {

stringRedisTemplate.opsForList().set(key, index, value);

return true;

} catch (Exception e) {

log.error("lUpdateIndex error", e);

return false;

}

}

/**

* 移除N个值为value

*

* @param key 键

* @param count 移除多少个

* @param value 值

* @return 移除的个数

*/

public long lRemove(String key, long count, Object value) {

try {

Long remove = stringRedisTemplate.opsForList().remove(key, count, value);

return remove;

} catch (Exception e) {

log.error("lRemove error", e);

return 0;

}

}

/*public Long incr(String key, long liveTime) {

RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());

Long increment = entityIdCounter.getAndIncrement();

//初始设置过期时间

if ((null == increment || increment.longValue() == 0) && liveTime > 0) {

entityIdCounter.expire(liveTime, TimeUnit.SECONDS);

}

return increment;

}*/

public Long incr(String key) {

return incr(key, 1L);

}

public Long decr(String key) {

return incr(key, -1L);

}

public Long incrWithExpireTime(String key, long time) {

Long l = incr(key, 1L);

expire(key, time);

return l;

}

public Long decrWithExpireTime(String key, long time) {

Long l = incr(key, -1L);

expire(key, time);

return l;

}

public Long incr(String key, long add) {

return stringRedisTemplate.execute((RedisCallback<Long>) con -> {

Long record = con.incrBy(toBytes(key), add);

return record == null ? 0L : record;

});

}

private byte[] toBytes(String key) {

nullCheck(key);

return key.getBytes(REDIS_CODE);

}

private void nullCheck(Object... args) {

for (Object obj : args) {

if (obj == null) {

throw new IllegalArgumentException("redis argument can not be null!");

}

}

}

public boolean addOnlinePlayer(String playerName, Integer id) {

boolean success = redisTemplate.opsForZSet().add("ONLINE_PLAYERS", playerName, id);

return success;

}

public boolean rmOnlinePlayer(String playerName) {

Long id = redisTemplate.opsForZSet().remove("ONLINE_PLAYERS", playerName);

return id > 0;

}

public boolean isOnlinePlayer(String playerName) {

Double score = redisTemplate.opsForZSet().score("ONLINE_PLAYERS", playerName);

if (null == score) {

return false;

}

return score.compareTo(new Double(0)) > 0;

}

}

测试结果

源码示例:https://gitee.com/lion123/springboot-redis-demo

 

以上是 springboot项目中使用redis缓存 的全部内容, 来源链接: utcz.com/z/514560.html

回到顶部