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);
    }
}

到此這篇關於SpringBoot整合RedisTemplate實現緩存信息監控的文章就介紹到這瞭,更多相關SpringBoot整合RedisTemplate內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: