SpringBoot整合RedisTemplate實現(xiàn)緩存信息監(jiān)控的步驟
SpringBoot 整合 Redis 數(shù)據(jù)庫實現(xiàn)數(shù)據(jù)緩存的本質是整合 Redis 數(shù)據(jù)庫,通過對需要“緩存”的數(shù)據(jù)存入 Redis 數(shù)據(jù)庫中,下次使用時先從 Redis 中獲取,Redis 中沒有再從數(shù)據(jù)庫中獲取,這樣就實現(xiàn)了 Redis 做數(shù)據(jù)緩存。
按照慣例,下面一步一步的實現(xiàn) Springboot 整合 Redis 來存儲數(shù)據(jù),讀取數(shù)據(jù)。
1.項目添加依賴首頁第一步還是在項目添加 Redis 的環(huán)境, 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的參數(shù)
spring:
### Redis Configuration
redis:
pool:
max-idle: 10
min-idle: 5
max-total: 20
hostName: 127.0.0.1
port: 63793.編寫一個 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.創(chuàng)建 JedisPoolConfig 對象。在該對象中完成一些連接池的配置
*/
@Bean
@ConfigurationProperties(prefix="spring.redis.pool")
public JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
return jedisPoolConfig;
}
/**
* 2.創(chuàng)建 JedisConnectionFactory:配置 redis 連接信息
*/
@Bean
@ConfigurationProperties(prefix="spring.redis")
public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(jedisPoolConfig);
return jedisConnectionFactory;
}
/**
* 3.創(chuàng)建 RedisTemplate:用于執(zhí)行 Redis 操作的方法
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
// 關聯(lián)
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.項目實戰(zhàn)中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中的數(shù)據(jù)
String wellArea = opsForValue.get(RedisConstants.REDIS_KEY_WELL_AREA);
//如果沒有去查數(shù)據(jù)庫
if (wellArea == null) {
List<String> wellAreaList = wellAreaDao.getAll();
wellArea = new ObjectMapper().writeValueAsString(wellAreaList);
//將查出來的數(shù)據(jù)存儲在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";
/**
* 井區(qū)塊
*/
String REDIS_KEY_WELL_AREA = "WELL-AREA";
/**
*
*/
long REDIS_TIMEOUT_1 = 1L;
}補充:SpringBoot整合RedisTemplate實現(xiàn)緩存信息監(jiān)控
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緩存命令統(tǒng)計信息
? ? ? ? //Properties commandStats = redisTemplate.getRequiredConnectionFactory().getConnection().info("commandstats");
? ? ? ? Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
? ? ? ? // 獲取redis緩存中可用鍵Key的總數(shù)
? ? ? ? //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實現(xiàn)緩存信息監(jiān)控的文章就介紹到這了,更多相關SpringBoot整合RedisTemplate內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- 在SpringBoot中注入RedisTemplate實例異常的解決方案
- SpringBoot整合Redis使用@Cacheable和RedisTemplate
- 詳解SpringBoot使用RedisTemplate操作Redis的5種數(shù)據(jù)類型
- SpringBoot整合Redis使用RedisTemplate和StringRedisTemplate
- springboot使用redisRepository和redistemplate操作redis的過程解析
- SpringBoot混合使用StringRedisTemplate和RedisTemplate的坑及解決
- SpringBoot集成RedisTemplate的實現(xiàn)示例
相關文章
從入門到實戰(zhàn)詳解如何使用Apache?POI操作Word文檔
Apache?POI是Java生態(tài)中最流行的Microsoft?Office文檔操作庫之一,它為Word文檔提供了全面的API支持,下面我們來看看如何使用Apache?POI進行word文檔的操作吧2025-06-06
spring boot mybatis多數(shù)據(jù)源解決方案過程解析
這篇文章主要介紹了spring boot mybatis多數(shù)據(jù)源解決方案過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-11-11

