引入pom依赖
<!-- redis --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> </dependency> <!-- jedis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <!-- fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.73</version> </dependency>
application.properties配置文件
#redis配置 spring.redis.database=2 spring.redis.host=xx.xx.xx.xx spring.redis.port=xxx spring.redis.password=xxxx spring.redis.pool.max-active=8 spring.redis.pool.max-wait=-1 spring.redis.pool.max-idle=8 spring.redis.pool.min-idle=0 spring.redis.timeout=1000
Redis配置类,RedisConfig.java
import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.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.JsonInclude.Include; import com.fasterxml.jackson.databind.ObjectMapper; import redis.clients.jedis.JedisPoolConfig; /** * redis配置 可以在配置文件中修改连接参数 * <p>Title: RedisConfig</p> * <p>Description: </p> * @author nanfangzhe_xsz * @date 2021年8月23日 */ @Configuration("RedisConfig") public class RedisConfig { private static Logger log = LoggerFactory.getLogger(RedisConfig.class); @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.password}") private String password; @Value("${spring.redis.database}") private int database; @Value("${spring.redis.timeout}") private int timeout; @Value("${spring.redis.pool.max-active}") private int maxActive; @Value("${spring.redis.pool.max-idle}") private int maxIdle; @Value("${spring.redis.pool.min-idle}") private int minIdle; @Value("${spring.redis.pool.max-wait}") private long maxWait; @Bean public JedisConnectionFactory jedisConnectionFactory() { JedisConnectionFactory factory = new JedisConnectionFactory(); factory.setHostName(host); factory.setPort(port); factory.setPassword(password); factory.setDatabase(database); factory.setTimeout(timeout); JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(maxActive); jedisPoolConfig.setMaxIdle(maxIdle); jedisPoolConfig.setMinIdle(minIdle); jedisPoolConfig.setMaxWaitMillis(maxWait); factory.setPoolConfig(jedisPoolConfig); return factory; } @Bean(name = "redisTemplate") // @Primary // @Primary:自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常 public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory factory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>(); redisTemplate.setConnectionFactory(factory); // Json序列化配置 使用Jackson2JsonRedisSerialize 替换默认序列化 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper objectMapper = new ObjectMapper(); // 序列化的时候序列对象的所有属性 objectMapper.setSerializationInclusion(Include.ALWAYS); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); // 设置value的序列化规则和 key的序列化规则 redisTemplate.setKeySerializer(stringRedisSerializer); redisTemplate.setHashKeySerializer(stringRedisSerializer); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
项目重启恢复对象数据,InitRedis.java
import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSON; import com.nfz.demo.entity.PersonBean; import com.nfz.demo.global.StatusMap; @Component public class InitRedis implements ApplicationRunner { @Autowired private RedisTemplate<String, ?> redisTemplate; // 恢复redis中的数据 @Override @Async public void run(ApplicationArguments args) throws Exception { // 获取redis中所有的keys值 Set<String> keys = redisTemplate.keys("*"); // PersonBean 这里定义是一个对象,name是一个属性 // redis数据库本身就是个map,所以这里 // key:PersonBean实体的name属性 // value:PersonBean实体 Map<String, PersonBean> hashMap = new HashMap<String, PersonBean>(); if (keys != null) { for (String name : keys) { // 获取Redis中,key对应的value Object one = redisTemplate.opsForValue().get(name); PersonBean dto = JSON.parseObject(JSON.toJSONString(one), PersonBean.class); hashMap.put(name, dto); } if (null != hashMap) { // 全局缓存恢复 StatusMap.setallStatusMap (hashMap); } } } }
缓存全局变量,StatusMap.java
package com.nfz.demo.global; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import com.nfz.demo.entity.PersonBean; public class StatusMap implements Serializable { /** * */ private static final long serialVersionUID = 7196410776097983398L; /* * 组件状态 */ public static Map<String, PersonBean> allStatusMap = new HashMap<String, PersonBean>();; public static synchronized Map<String, PersonBean> getallStatusMap () { return allStatusMap ; } public synchronized static void setAllStatusMap (Map<String, PersonBean> allStatusMap ) { StatusMap.AllStatusMap = allStatusMap ; } public static void addPersonStatus(String name, PersonBean person) { allStatusMap.put(name, person); } public static void removePersonStatus(String name) { allStatusMap.remove(name); } }
Redis操作展示(增加、删除、查询)
@Autowired private RedisTemplate<String, ?> redisTemplate; public static void main(String[] args) { // 去掉Redis页面翻译状态 Object one = redisTemplate.opsForValue().get(name); if (one != null) { redisTemplate.delete(name); } // 存入单个信息 redisTemplate.opsForValue().set(name, StatusMap.getallStatusMap().get(name)); // 存入单个信息,五分钟后自动删除 redisTemplate.opsForValue().set(name, StatusMap.getallStatusMap().get(name), 5, TimeUnit.MINUTES); // 获取redis中所有的keys值 Set<String> keys = redisTemplate.keys("*"); if (keys != null) { for (String name : keys) { // 获取Redis中,key对应的value Object one = redisTemplate.opsForValue().get(name); System.out.println("当前的name:" + name + " - PersonBean:" + one); } } }