SpringBoot整合RedisTemplate实现缓存信息监控的步骤
作者:夏的世界的伤 发布时间:2023-10-14 10:17:13
标签:SpringBoot,RedisTemplate,缓存信息监控
SpringBoot 整合 Redis 数据库实现数据缓存的本质是整合 Redis 数据库,通过对需要“缓存”的数据存入 Redis 数据库中,下次使用时先从 Redis 中获取,Redis 中没有再从数据库中获取,这样就实现了 Redis 做数据缓存。   
按照惯例,下面一步一步的实现 Springboot 整合 Redis 来存储数据,读取数据。
1.项目添加依赖首页第一步还是在项目添加 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>
2. 添加redis的参数
spring:
### Redis Configuration
redis:
pool:
max-idle: 10
min-idle: 5
max-total: 20
hostName: 127.0.0.1
port: 6379
3.编写一个 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;
/**
* 描述:Redis 配置类
*/
@Configuration
public class RedisConfig {
/**
* 1.创建 JedisPoolConfig 对象。在该对象中完成一些连接池的配置
*/
@Bean
@ConfigurationProperties(prefix="spring.redis.pool")
public JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
return jedisPoolConfig;
}
/**
* 2.创建 JedisConnectionFactory:配置 redis 连接信息
*/
@Bean
@ConfigurationProperties(prefix="spring.redis")
public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(jedisPoolConfig);
return jedisConnectionFactory;
}
/**
* 3.创建 RedisTemplate:用于执行 Redis 操作的方法
*/
@Bean
public 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;
}
}
4.使用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;
/**
* @Description 整合 Redis 测试Controller
* @version V1.0
*/
@RestController
public class RedisController {
@Autowired
private 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";
}
}
5.项目实战中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;
/**
* @author zhangkai
*
*/
@Service
public class WellAreaServiceImpl implements WellAreaService {
@Autowired
private WellAreaDao wellAreaDao;
@Autowired
private RedisTemplate<String, String> stringRedisTemplate;
/*
* (non-Javadoc)
*
* @see com.shiwen.lujing.service.WellAreaService#getAll()
*/
@Override
public 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;
}
}
6.redis中使用的key
package com.shiwen.lujing.util;
/**
* redis 相关常量
*
*
*/
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实现缓存信息监控
1、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);
}
}
来源:https://www.cnblogs.com/hkMblogs/p/15059454.html


猜你喜欢
- 在笔试编程过程中,关于数据的读取如果迷迷糊糊,那后来的编程即使想法很对,实现很好,也是徒劳,于是在这里认真总结了Java Scanner 类
- 前言最近,在给项目组使用Spring搭建Java项目基础框架时,发现使用Spring提供的BeanPostProcessor可以很简单方便地
- 本文实例为大家分享了java实现简单的猜数字的具体代码,供大家参考,具体内容如下题目描述:猜数字(又称 Bulls and Cows )是一
- namespace ConsoleApplication2 { class Program { static v
- 一 前言redis在分布式应用十分广泛,本篇文章也是互联网面试的重点内容,读者至少需要知道为什么需要分布式锁,分布式锁的实现原理,分布式锁的
- 1.概念a.是个二叉树(每个节点最多有两个子节点)b.对于这棵树中的节点的节点值左子树中的所有节点值 < 根节点 < 右子树的所
- 1.前置准备默认服务器上的hadoop服务已经启动本地如果是windows环境,需要本地配置下hadoop的环境变量本地配置hadoop的环
- 最近项目里面做了一个定时器,结果报错这个。网上的原因大多说是什么版本问题。我记录下我的问题所在。由于项目启动在局域网,不能访问互联网。打出来
- 前言公司最近在开发中遇到一个问题,在弄帖子的发布与回复问题,然后再iOS端和Android端添加表情的时候都会出错Caused by: ja
- IDEA快速搭建spring boot项目1.创建项目老规矩,点击Create New Project2.编写控制器在com.demo.sp
- 现在很多安全类的软件,比如360手机助手,百度手机助手等等,都有一个悬浮窗,可以飘浮在桌面上,方便用户使用一些常用的操作。首先,看一下效果图
- 利用Javaweb开发的一个校园服务系统,通过发布自己的任务并设置悬赏金额,有些类似于赏金猎人,在这里分享给大家,有需要可以联系我:2186
- 一、this关键字的作用this关键字除了可以强调本类中的方法还具有以下作用。1.表示类中的属性2.可以使用关键字调用本类中的构造方法3.t
- .net core提供了Json处理模块,在命名空间System.Text.Json中,下面通过顶级语句,对C#的Json功能进行讲解。序列
- 一、什么是桥接模式:桥接,顾名思义,就是用来连接两个部分,使得两个部分可以互相通讯,桥接模式的作用就是为被分离的抽象部分和实现部分搭桥。在现
- 本文实例讲述了C#反射应用。分享给大家供大家参考。具体如下:通过反射实现多系统数据库的配置通过定义接口,反射实例化配置的节点的值配置App.
- 调用native 方法来开启和关闭vibrator: native static void vibratorOn(long millisec
- 前言该文章为对工作中部分业务实现的总结,阅读时间:20分钟,版本:Android 6.0 - 9.0 update time 2021年02
- 什么是RabbitMQ?RabbitMQ是由erlang语言开发的一个基于AMQP(Advanced Message Queuing Pro
- 本文实例为大家分享了C#实现温度转换功能的具体代码,供大家参考,具体内容如下界面图代码using System;using System.C