溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringBoot整合RedisTemplate如何實(shí)現(xiàn)緩存信息監(jiān)控

發(fā)布時(shí)間:2022-01-24 09:33:24 來源:億速云 閱讀:199 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)SpringBoot整合RedisTemplate如何實(shí)現(xiàn)緩存信息監(jiān)控的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。

SpringBoot 整合 Redis 數(shù)據(jù)庫實(shí)現(xiàn)數(shù)據(jù)緩存的本質(zhì)是整合 Redis 數(shù)據(jù)庫,通過對(duì)需要“緩存”的數(shù)據(jù)存入 Redis 數(shù)據(jù)庫中,下次使用時(shí)先從 Redis 中獲取,Redis 中沒有再從數(shù)據(jù)庫中獲取,這樣就實(shí)現(xiàn)了 Redis 做數(shù)據(jù)緩存。 

按照慣例,下面一步一步的實(shí)現(xiàn) Springboot 整合 Redis 來存儲(chǔ)數(shù)據(jù),讀取數(shù)據(jù)。

1.項(xiàng)目添加依賴首頁第一步還是在項(xiàng)目添加 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: 6379

3.編寫一個(gè) RedisConfig 注冊(cè)到 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 對(duì)象。在該對(duì)象中完成一些連接池的配置
	 */
	@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<>();
		
		// 關(guān)聯(lián)
		redisTemplate.setConnectionFactory(jedisConnectionFactory);
		// 為 key 設(shè)置序列化器
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		// 為 value 設(shè)置序列化器
		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 測(cè)試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);
		
		//添加對(duì)象
		//重新設(shè)置序列化器
		redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
		redisTemplate.opsForValue().set("users", new Users("1" , "張三"));
		
		//獲取對(duì)象
		//重新設(shè)置序列化器
		redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
		Users user = (Users)redisTemplate.opsForValue().get("users");
		System.out.println(user);
		
		//以json格式存儲(chǔ)對(duì)象
		//重新設(shè)置序列化器
		redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Users.class));
		redisTemplate.opsForValue().set("usersJson", new Users("2" , "李四"));
		
		//以json格式獲取對(duì)象
		//重新設(shè)置序列化器
		redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Users.class));
		user = (Users)redisTemplate.opsForValue().get("usersJson");
		System.out.println(user);
		
		return "home";
	}
}

5.項(xiàng)目實(shí)戰(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ù)存儲(chǔ)在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:過期時(shí)間;  unit:時(shí)間單位  
            //使用:redisTemplate.opsForValue().set("name","tom",10, TimeUnit.SECONDS);
            //redisTemplate.opsForValue().get("name")由于設(shè)置的是10秒失效,十秒之內(nèi)查詢有結(jié)
            //果,十秒之后返回為null 
		}
		return wellArea;
	}
}

6.redis中使用的key

package com.shiwen.lujing.util;
/**
 * redis 相關(guān)常量
 * 
 *
 */
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;
}

補(bǔ)充:SpringBoot整合RedisTemplate實(shí)現(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')")// 自定義權(quán)限注解
    @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)計(jì)信息
        //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);
    }
}

感謝各位的閱讀!關(guān)于“SpringBoot整合RedisTemplate如何實(shí)現(xiàn)緩存信息監(jiān)控”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI