整合Redis特意在此记录一下,方便后续查阅。
Maven 依赖
(1)本文所采用的SpringBoot的版本如下
org.springframework.boot
spring-boot-starter-parent
2.0.6.RELEASE
(2)加入Redis相关依赖
org.springframework.boot
spring-boot-starter-data-redis
redis.clients
jedis
application.xml中加入redis相关配置
spring:
redis:
database: 0 #数据库名
host: 127.0.0.1 #服务器地址
password:
port: 6379
pool:
max-idle: 10
min-idle: 8
max-active: 10000
max-wait: 2000
testOnBorrow: true
testOnReturn: true
testWhileIdle: true
sentinel:
master:
nodes: 127.0.0.1:6379
timeout: 2000 #毫秒
写一个redis配置类
package com.example.demo;
import org.springframework.beans.factory.annotation.Value;
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.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.pool.max-idle}")
private int max_idle;
@Value("${spring.redis.pool.min-idle}")
private int min_idle;
@Value("${spring.redis.pool.max-wait}")
private int max_wait;
@Value("${spring.redis.pool.max-active}")
private int max_active;
@Value("${spring.redis.pool.testOnBorrow}")
private boolean testOnBorrow;
@Value("${spring.redis.sentinel.master}")
private String master;
@Value("${spring.redis.sentinel.nodes}")
private String nodes;
@Bean
JedisConnectionFactory jedisConnectionFactory() {
// 单点配置
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(max_idle);
jedisPoolConfig.setMaxWaitMillis(max_wait);
jedisPoolConfig.setMinIdle(min_idle);
jedisPoolConfig.setMaxTotal(max_active);
jedisPoolConfig.setTestOnBorrow(testOnBorrow);
JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory(jedisPoolConfig);
redisConnectionFactory.setPassword(password);
redisConnectionFactory.setHostName(host);
redisConnectionFactory.setPort(port);
return redisConnectionFactory;
}
@Bean
@SuppressWarnings("all")
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
RedisTemplate template = new RedisTemplate();
template.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);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
Redis 方法类 RedisUtil .java
package com.example.demo;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
@Component
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
/**
* 指定缓存失效时间
* @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(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
写一个简单的实体类 UserDto .java
package com.example.demo;
import lombok.Data;
@Data
public class UserDto {
private String name;
private int age;
}
这个demo 没有使用数据库,直接用写死的数据来进行测试,使用的是springboot 的测试方式
//注入redis 工具
@Autowired
private RedisUtil redisUtil;
@Test
public void contextLoads() {
UserDto user = new UserDto();
user.setAge(12);
user.setName("测试姓名");
redisUtil.set("user", user);
try {
redisUtil.get("user");
} catch (Exception e) {
log.error("获取Redis数据失败"+e);
}
UserDto userDto = (UserDto)redisUtil.get("user");
System.out.println("我的名字叫"+userDto.getName()+",我今年"+userDto.getAge()+"岁了!");
}
运行结果
参考文章 https://www.cnblogs.com/zeng1994/p/03303c805731afc9aa9c60dbbd32a323.html