欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot整合RedisTemplate实现缓存信息监控的步骤

程序员文章站 2022-06-24 16:37:39
springboot 整合 redis 数据库实现数据缓存的本质是整合 redis 数据库,通过对需要“缓存”的数据存入 redis 数据库中,下次使用时先从 redis 中获...

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内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!