这篇文章给大家分享的是有关SpringBoot整合RedisTemplate如何实现缓存信息监控的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。springBoot 整合 Redis 数据库实现数据缓存的本质是整合
这篇文章给大家分享的是有关SpringBoot整合RedisTemplate如何实现缓存信息监控的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
springBoot 整合 Redis 数据库实现数据缓存的本质是整合 Redis 数据库,通过对需要“缓存”的数据存入 Redis 数据库中,下次使用时先从 Redis 中获取,Redis 中没有再从数据库中获取,这样就实现了 Redis 做数据缓存。
按照惯例,下面一步一步的实现 Springboot 整合 Redis 来存储数据,读取数据。
项目添加依赖首页第一步还是在项目添加 Redis 的环境, Jedis。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId></dependency>
添加redis的参数
spring: ### Redis Configuration redis: pool: max-idle: 10 min-idle: 5 max-total: 20 hostName: 127.0.0.1 port: 6379
编写一个 RedisConfig 注册到 Spring 容器
package com.config;import org.springframework.boot.context.properties.ConfigurationProperties;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.StringRedisSerializer;import redis.clients.jedis.JedisPoolConfig;@Configurationpublic class RedisConfig {@Bean@ConfigurationProperties(prefix="spring.redis.pool")public JedisPoolConfig jedisPoolConfig() {JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();return jedisPoolConfig;}@Bean@ConfigurationProperties(prefix="spring.redis")public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig) {JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(jedisPoolConfig);return jedisConnectionFactory;}@Beanpublic RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();// 关联redisTemplate.setConnectionFactory(jedisConnectionFactory);// 为 key 设置序列化器redisTemplate.seTKEySerializer(new StringRedisSerializer());// 为 value 设置序列化器redisTemplate.setValueSerializer(new StringRedisSerializer());return redisTemplate;}}
使用redisTemplate
package com.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.Jackson2JSONRedisSerializer;import org.springframework.data.redis.serializer.jdkSerializationRedisSerializer;import org.springframework.WEB.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.bean.Users;@RestControllerpublic class RedisController {@Autowiredprivate RedisTemplate<String, Object> redisTemplate;@RequestMapping("/redishandle")public String redishandle() {//添加字符串redisTemplate.opsForValue().set("author", "欧阳");//获取字符串String value = (String)redisTemplate.opsForValue().get("author");System.out.println("author = " + value);//添加对象//重新设置序列化器redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());redisTemplate.opsForValue().set("users", new Users("1" , "张三"));//获取对象//重新设置序列化器redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());Users user = (Users)redisTemplate.opsForValue().get("users");System.out.println(user);//以json格式存储对象//重新设置序列化器redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Users.class));redisTemplate.opsForValue().set("usersJson", new Users("2" , "李四"));//以json格式获取对象//重新设置序列化器redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Users.class));user = (Users)redisTemplate.opsForValue().get("usersJson");System.out.println(user);return "home";}}
项目实战中redisTemplate的使用
package com.shiwen.lujing.service.impl;import java.util.List;import java.util.concurrent.TimeUnit;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.ValueOperations;import org.springframework.stereotype.Service;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import com.shiwen.lujing.dao.mapper.WellAreaDao;import com.shiwen.lujing.service.WellAreaService;import com.shiwen.lujing.util.RedisConstants;@Servicepublic class WellAreaServiceImpl implements WellAreaService {@Autowiredprivate WellAreaDao wellAreaDao;@Autowiredprivate RedisTemplate<String, String> stringRedisTemplate;@Overridepublic String getAll() throws JsonProcessingException {//redis中key是字符串ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();//通过key获取redis中的数据String wellArea = opsForValue.get(RedisConstants.REDIS_KEY_WELL_AREA);//如果没有去查数据库if (wellArea == null) {List<String> wellAreaList = wellAreaDao.getAll();wellArea = new ObjectMapper().writeValueAsString(wellAreaList);//将查出来的数据存储在redis中opsForValue.set(RedisConstants.REDIS_KEY_WELL_AREA, wellArea, RedisConstants.REDIS_TIMEOUT_1, TimeUnit.DAYS); // set(K key, V value, long timeout, TimeUnit unit) //timeout:过期时间; unit:时间单位 //使用:redisTemplate.opsForValue().set("name","tom",10, TimeUnit.SECONDS); //redisTemplate.opsForValue().get("name")由于设置的是10秒失效,十秒之内查询有结 //果,十秒之后返回为null }return wellArea;}}
redis中使用的key
package com.shiwen.lujing.util;public interface RedisConstants {String REDIS_KEY_JING_SHOU_ZI = "JING-SHOU-ZI";String REDIS_KEY_WELL_AREA = "WELL-AREA";long REDIS_TIMEOUT_1 = 1L;}
补充:SpringBoot整合RedisTemplate实现缓存信息监控
CacheController接口代码
@RestController@RequestMapping("/monitor/cache")public class CacheController{ @Autowired private RedisTemplate<String, String> redisTemplate; @PreAuthorize("@ss.hasPermi('monitor:cache:list')")// 自定义权限注解 @GetMapping() public ajaxResult getInfo() throws Exception { // 获取redis缓存完整信息 //Properties info = redisTemplate.getRequiredConnectionFactory().getConnection().info(); Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info()); // 获取redis缓存命令统计信息 //Properties commandStats = redisTemplate.getRequiredConnectionFactory().getConnection().info("commandstats"); Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats")); // 获取redis缓存中可用键Key的总数 //Long dbSize = redisTemplate.getRequiredConnectionFactory().getConnection().dbSize(); Object dbSize = redisTemplate.execute((RedisCallback<Object>) connection -> connection.dbSize()); Map<String, Object> result = new HashMap<>(3); result.put("info", info); result.put("dbSize", dbSize); List<Map<String, String>> pieList = new ArrayList<>(); commandStats.stringPropertyNames().forEach(key -> { Map<String, String> data = new HashMap<>(2); String property = commandStats.getProperty(key); data.put("name", StringUtils.removeStart(key, "cmdstat_")); data.put("value", StringUtils.substringBetween(property, "calls=", ",usec")); pieList.add(data); }); result.put("commandStats", pieList); return AjaxResult.success(result); }}
感谢各位的阅读!关于“SpringBoot整合RedisTemplate如何实现缓存信息监控”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
--结束END--
本文标题: SpringBoot整合RedisTemplate如何实现缓存信息监控
本文链接: https://lsjlt.com/news/321157.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0