redis是什么?
redis是key-value 数据库,速度快,同时还提供list,set,zset,hash等数据结构的存储
java代码任何使用redis?
1.使用数据库连接池,使用Jedis的客户端
2.使用RedisTemplate 类
<dependency>
<groupId>redis.clientsgroupId>
<artifactId>jedisartifactId>
<version>2.8.1version>
<type>jartype>
dependency>
redis客户端初始化,放在启动类下
//redis客户端注入,初始化
@Bean(name = "shardedJedisPool")
public ShardedJedisPool shardedJedisPool() {
JedisShardInfo shardInfo = new JedisShardInfo("127.0.0.1", 6379);
List<JedisShardInfo> shardInfoList = Lists.newArrayList(shardInfo);
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
ShardedJedisPool shardedJedisPool = new ShardedJedisPool(config, shardInfoList);
return shardedJedisPool;
}
redis工具类
redis操作,①先获取连接 ②调用底层redis的方法 ③关闭连接
package com.next.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import javax.annotation.Resource;
/**
* @desc redis操作,①先获取连接 ②调用底层redis的方法 ③关闭连接
*/
@Service
@Slf4j
public class RedisUtils {
@Resource(name ="shardedJedisPool")
private ShardedJedisPool shardedJedisPool;
//获取其中一个连接
private ShardedJedis instance(){
return shardedJedisPool.getResource();
}
//关闭连接
private void safeClose(ShardedJedis shardedJedis){
try {
if(null!=shardedJedis){
shardedJedis.close();
}
}catch (Exception e){
log.error("jedis close exception",e);
}
}
//set方法
public void set(String cacheKey,String value){
if(null == value){
return;
}
ShardedJedis shardedJedis = null;
try {
shardedJedis = instance();
shardedJedis.set(cacheKey, value);
}catch (Exception e){
log.error("jedis set exception,cacheKey:{},value:{}",cacheKey,value);
throw e;
}finally {
safeClose(shardedJedis);
}
}
//get 方法
public String get(String cacheKey){
ShardedJedis shardedJedis = null;
try {
shardedJedis = instance();
return shardedJedis.get(cacheKey);
}catch (Exception e){
log.error("jedis get exception,cacheKey:{}",cacheKey);
throw e;
}finally {
safeClose(shardedJedis);
}
}
//hash存储
public void hset(String cacheKey,String field,String value){
ShardedJedis shardedJedis = null;
try {
shardedJedis = instance();
shardedJedis.hset(cacheKey, field, value);
}catch (Exception e){
log.error("jedis hset exception,cacheKey:{},field:{},value:{}",cacheKey,field,value);
throw e;
}finally {
safeClose(shardedJedis);
}
}
//hash存储(增加数量)
public void hincr(String cacheKey,String field,Long value){
ShardedJedis shardedJedis = null;
try {
shardedJedis = instance();
shardedJedis.hincrBy(cacheKey, field, value);
}catch (Exception e){
log.error("jedis hincrBy exception,cacheKey:{},field:{},value:{}",cacheKey,field,value);
throw e;
}finally {
safeClose(shardedJedis);
}
}
}
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
<version>2.7.3version>
dependency>
redisTemplate配置类
package com.redis.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @ClassDescription: redisTemplate配置类
* 配置工厂
* 序列化处理(解决redis客户端工具显示序列化导致的二进制)
* 创建对象(解决了redisTemplate为null的问题)
*/
@Configuration
public class RedisConfig {
@Bean(name = "redisTemplate")
public RedisTemplate redisTemplate(RedisConnectionFactory factory){
System.out.println("redis序列化-->");
RedisTemplate redisTemplate = new RedisTemplate();
RedisSerializer redisSerializer = new StringRedisSerializer();
//连接工厂
redisTemplate.setConnectionFactory(factory);
//键序列化
redisTemplate.setKeySerializer(redisSerializer);
//值序列化
redisTemplate.setValueSerializer(redisSerializer);
//key hashMap序列化
redisTemplate.setHashKeySerializer(redisSerializer);
//value hashMap序列化
redisTemplate.setHashValueSerializer(redisSerializer);
return redisTemplate;
}
}
redisTemplate工具类
package com.redis.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* @ClassDescription: redisTemplate工具类
* 注: 同一个键存再次进行存储就是修改操作
*
* @Author:李白
* @Date:2023/4/6 10:12
*/
@Component
public class RedisTemplateUtil implements Serializable {
@Autowired
private RedisTemplate redisTemplate;
private static RedisTemplate redisTem;
@PostConstruct
public void initRedisTem(){
redisTem = redisTemplate;
}
/**
* 判断redis中是否含有该键
* @param key 键值
* @return Boolean值 false 没有此键, true 含有此键
*/
public static boolean hasKey(String key){
//返回boolean值
return redisTem.hasKey(key);
}
/**
* 获取键的过期时间
* @param key 键
* @return 返回long类型的时间数值
*/
public static long getExpire(String key){
return redisTem.getExpire(key);
}
/**
* 过期时间设置
* @param key 键
* @param expireMinutes 过期时间
* @return 返回设置成功
*/
public static boolean setExpireByMillis(String key, long expireMillis){
Boolean expire = redisTem.expire(key, Duration.ofMillis(expireMillis));
return expire;
}
/**
* 删除键值
* @param key 键
* @return 返回删除结果
*/
public static boolean delete(String key){
Boolean delete = redisTem.delete(key);
return delete;
}
//-----------------------------对象键值存取---------------------------------------------------------------
/**
* 存值
* @param key 键
* @param value 值
*/
public static void set(Object key, Object value){
redisTem.opsForValue().set(key, value);
}
/**
* 存值
* @param key 键
* @param value 值
* @param timeout 过期时间
*/
public static void set(Object key, Object value, Duration timeout){
redisTem.opsForValue().set(key, value, timeout);
}
/**
* 获取键对应的值
* @param key 键
* @return 返回键对应的值
*/
public static Object get(Object key){
Object value = redisTem.opsForValue().get(key);
return value;
}
//-----------------------------String键值存取---------------------------------------------------------------
/**
* 存值
* @param key 键
* @param value 值
*/
public static void set(String key, String value){
redisTem.opsForValue().set(key, value);
}
/**
* 存值
* @param key 键
* @param value 值
* @param timeout 过期时间 可以使用Duration来调用相关时间参数
*/
public static void set(String key, String value, Duration timeout){
redisTem.opsForValue().set(key, value, timeout);
}
/**
* 存值(时间封装)
* @param key 键
* @param value 值
* @param minutes 过期时间 分钟
*/
public static void setBySeconds(String key, String value, long seconds){
redisTem.opsForValue().set(key, value, Duration.ofSeconds(seconds));
}
/**
* 获取键对应的值
* @param key 键
* @return 返回键对应的值
*/
public static Object get(String key){
Object value = redisTem.opsForValue().get(key);
return value;
}
/**
* 获取键对应的值
* @param key 键
* @param start 开始位置
* @param end 结束位置
* @return 返回范围内的对应键的值
*/
public static Object get(String key, long start, long end){
Object value = redisTem.opsForValue().get(key, start, end);
return value;
}
//-----------------------------List键值存取---------------------------------------------------------------
/**
* 根据key存储到list的指定位置
* @param key 键
* @param index list中指定索引
* @param value 值
*/
public static void lSet(Object key, long index, Object value){
redisTem.opsForList().set(key, index, value);
}
/**
* 存储到列表最左侧
* @param key 键
* @param value 值
*/
public static void lSet(Object key, Object value){
redisTem.opsForList().leftPush(key, value);
}
/**
* 存储到列表最右
* @param key 键
* @param value 值
*/
public static void lSetR(Object key, Object value){
redisTem.opsForList().rightPush(key, value);
}
/**
* 获取键对应的列表数据
* @param key 键
* @param start 开始位置
* @param end 结束位置
* @return 返回key对应范围内的列表数据
*/
public static List lGet(Object key, long start, long end){
List list = redisTem.opsForList().range(key, start, end);
return list;
}
//-----------------------------Set(无序)键值存取---------------------------------------------------------------
/**
* 存储set类型的数据
* @param key 键
* @param values 值,可以是多个
*/
public static void sSet(Object key, Object... values){
redisTem.opsForSet().add(key, values);
}
/**
* 获取set类型的数据
* @param key 键
* @return 返回一个set集合
*/
public static Set sGet(Object key){
Set members = redisTem.opsForSet().members(key);
return members;
}
//-----------------------------ZSet(有序)键值存取---------------------------------------------------------------
/**
* 存储有序集合
* @param key 键
* @param value 值
* @param score 排序
*/
public static void zSet(Object key, Object value, double score){
redisTem.opsForZSet().add(key, value, score);
}
/**
* 存储值
* @param key 键
* @param set 集合
*/
public static void zSet(Object key, Set set){
redisTem.opsForZSet().add(key, set);
}
/**
* 获取key指定范围的值
* @param key 键
* @param start 开始位置
* @param end 结束位置
* @return 返回set
*/
public static Set zGet(Object key, long start, long end){
Set set = redisTem.opsForZSet().range(key, start, end);
return set;
}
//-----------------------------HashMap键值存取---------------------------------------------------------------
/**
* 存储hashMap数据
* @param key 键
* @param hashKey map的id
* @param value 值
*/
public static void hSet(Object key, Object hashKey, Object value){
redisTem.opsForHash().put(key, hashKey, value);
}
/**
* 获取hashMap数据
* @param key 键
* @param hashKey map的id
* @return 返回值
*/
public static Object hGet(Object key, Object hashKey){
Object o = redisTem.opsForHash().get(key, hashKey);
return o;
}
/**
* 删除数据
* @param key 键
* @param hashKeys map的id
* @return 返回Boolean
*/
public static Object hDel(Object key, Object... hashKeys){
Long delete = redisTem.opsForHash().delete(key, hashKeys);
return delete;
}
}
参考文章Redis在Java中的基本使用,RedisTemplate 工具类