Redis缓存java端实现

redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set –有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。

1. 引入redis依赖
1
2
3
4
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
2.在application.properties添加redis配置文件
1
2
3
4
5
6
7
8
#redis
redis.host=127.0.0.1
redis.port=6379
redis.timeout=3
redis.password=2966
redis.poolMaxTotal=10 //资源池中最大连接数
redis.poolMaxIdle=10 //允许的最大空闲的连接数
redis.poolMaxWait=3
3.定义redis的类,引入redis的配置
1
2
3
4
5
6
7
8
9
10
11
12
13
@Component
@ConfigurationProperties(prefix="redis")
@Data
public class RedisConfig {
private String host;
private int port;
private int timeout;//秒
private String password;
private int poolMaxTotal;
private int poolMaxIdle;
private int poolMaxWait;//秒

}
4.RedisPoolFactory类,用于返回一个redis池
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Service
public class RedisPoolFactory {
@Autowired
RedisConfig redisConfig;
@Bean
public JedisPool JedisPoolFactory() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
//允许最大空闲的连接数
poolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());
//资源池中最大连接数
poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());
//最大等待毫秒数
poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * 1000);
JedisPool jp = new JedisPool(poolConfig,
redisConfig.getHost(),
redisConfig.getPort(),

redisConfig.getTimeout()*1000,

redisConfig.getPassword(), 0);

return jp;
}

}
5.编写RedisService类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Service

public class RedisService {

@Autowired
JedisPool jedisPool;
//里面编写redis操作:增删改查
private void returnToPool(Jedis jedis) {

if(jedis != null) {
jedis.close();
}
}

}
5.1 获取单个对象(get)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//相当于redis里面的get key 
public <T> T get(KeyPrefix prefix, String key, Class<T> clazz) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key,之前设置通用缓存key时的key设为className:key
String realKey = prefix.getPrefix() + key;
//跟redis里面的获取一个key操作一致
String str = jedis.get(realKey);
//将结果转换成一个java对象
T t = stringToBean(str, clazz);
return t;
}finally {
//关闭池资源
returnToPool(jedis);
}
}
//json转换为java对象
public static <T> T stringToBean(String str, Class<T> clazz) {
if(str == null || str.length() <= 0 || clazz == null) {
return null;
}
//判断类型
if(clazz == int.class || clazz == Integer.class) {
return (T)Integer.valueOf(str);
}else if(clazz == String.class) {
return (T)str;
}else if(clazz == long.class || clazz == Long.class) {
return (T)Long.valueOf(str);
}else {
return JSON.toJavaObject(JSON.parseObject(str), clazz);
}
}
5.2 设置对象(set)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//相当于redis里面的set key value
public <T> boolean set(KeyPrefix prefix, String key, T value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//对象转换为json字符串
String str = beanToString(value);
if(str == null || str.length() <= 0) {
return false;
}
//生成真正的key
String realKey = prefix.getPrefix() + key;
//获取过期时间
int seconds = prefix.expireSeconds();
if(seconds <= 0) {
//永久有效,无过期时间
jedis.set(realKey, str);
}else {
//为指定的 key 设置值及其过期时间。
jedis.setex(realKey, seconds, str);
}
return true;
}finally {
returnToPool(jedis);
}
}
//将对象转化为Json字符串
public static <T> String beanToString(T value) {
if(value == null) {
return null;
}
Class<?> clazz = value.getClass();
if(clazz == int.class || clazz == Integer.class) {
return ""+value;
}else if(clazz == String.class) {
return (String)value;
}else if(clazz == long.class || clazz == Long.class) {
return ""+value;
}else {
return JSON.toJSONString(value);
}
}
5.3 判断key是否存在(exists)
1
2
3
4
5
6
7
8
9
10
11
12
//想当于redis里面的 exists key
public <T> boolean exists(KeyPrefix prefix, String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix() + key;
return jedis.exists(realKey);
}finally {
returnToPool(jedis);
}
}
5.4 增加值(incr)
1
2
3
4
5
6
7
8
9
10
11
12
//相当于redis里面的incr key_name
public <T> Long incr(KeyPrefix prefix, String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix() + key;
return jedis.incr(realKey);
}finally {
returnToPool(jedis);
}
}
5.5 减少值(decr)
1
2
3
4
5
6
7
8
9
10
11
12
//相当于redis里面的decr key_name
public <T> Long decr(KeyPrefix prefix, String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix() + key;
return jedis.decr(realKey);
}finally {
returnToPool(jedis);
}
}
5.6 删除(del)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//相当于redis里面的del key_name
//已知key
public boolean delete(KeyPrefix prefix, String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix() + key;
long ret = jedis.del(realKey);
return ret > 0;
}finally {
returnToPool(jedis);
}
}
//通过正则匹配删除 某key
public boolean delete(KeyPrefix prefix) {
if(prefix == null) {
return false;
}
List<String> keys = scanKeys(prefix.getPrefix());
if(keys==null || keys.size() <= 0) {
return true;
}
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.del(keys.toArray(new String[0]));
return true;
} catch (final Exception e) {
e.printStackTrace();
return false;
} finally {
if(jedis != null) {
jedis.close();
}
}
}
public List<String> scanKeys(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
List<String> keys = new ArrayList<String>();
String cursor = "0";
//scan搜索
ScanParams sp = new ScanParams();
sp.match("*"+key+"*");
//设置scan的个数
sp.count(100);
do{
ScanResult<String> ret = jedis.scan(cursor, sp);
//返回结果
List<String> result = ret.getResult();
if(result!=null && result.size() > 0){
//搜索的结果存入list
keys.addAll(result);
}
//再处理cursor,用于返回下次遍历的游标
cursor = ret.getStringCursor();
}while(!cursor.equals("0"));
return keys;
} finally {
if (jedis != null) {
jedis.close();
}
}
}
6.controller层测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Autowired
RedisService redisService;

@RequestMapping("/redis/get")
@ResponseBody
public Result<User> getRedis(){
User user = redisService.get(UserKey.getById,"key1",User.class);
return Result.success(user);
}
@RequestMapping("/redis/set")
@ResponseBody
public Result<Boolean> setRedis(){
User user = new User();
user.setId(1);
user.setName("1111");
redisService.set(UserKey.getById,""+1,user);
return Result.success(true);
}
文章目录
  1. 1. 1. 引入redis依赖
  2. 2. 2.在application.properties添加redis配置文件
  3. 3. 3.定义redis的类,引入redis的配置
  4. 4. 4.RedisPoolFactory类,用于返回一个redis池
  5. 5. 5.编写RedisService类
    1. 5.1. 5.1 获取单个对象(get)
    2. 5.2. 5.2 设置对象(set)
    3. 5.3. 5.3 判断key是否存在(exists)
    4. 5.4. 5.4 增加值(incr)
    5. 5.5. 5.5 减少值(decr)
    6. 5.6. 5.6 删除(del)
  6. 6. 6.controller层测试
| 139.6k