springboot中使用redistemplate实现redis数据缓存

求知若渴的蜗牛      2022-05-19     691

关键词:

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中使用thymeleaf

SpringBoot支持FreeMarker、Groovy、Thymeleaf和Mustache四种模板解析引擎,官方推荐使用Thymeleaf。spring-boot-starter-thymeleaf在SpringBoot中使用Thymeleaf只需在pom中加入Thymeleaf的starter即可:1234<dependency><groupId>org.sprin 查看详情

springboot中使用kafka

...oducer、以及consumer后,尝试在JAVA中使用Kafka。使用IDEA创建SpringBoot项目这个使用IDEA创建一个新的SpringBoot项目就可以,也可以在https://start.spring.io/下载一个新的项目。配置依赖 pom文件如下:1<?xmlversion="1.0" 查看详情

在springboot中使用httpinvoker

https://blog.csdn.net/qq_34741165/article/details/88146067 在Spring中使用HttpInvoker在官方文档中已经描述的很清楚了,那么,在SpringBoot中怎么使用呢?首先我们定义一个接口:publicinterfaceITestService{Stringtest(Stringhello);} 查看详情

springboot中使用jdbctemplate

本文将介绍如何将springboot与JdbcTemplate一起工作。Spring对数据库的操作在jdbc上面做了深层次的封装,使用spring的注入功能,可以把DataSource注册到JdbcTemplate之中。JdbcTemplate是在JDBCAPI基础上提供了更抽象的封装,并提供了基于方法... 查看详情

springboot中如何使用外置tomcat服务器

文章目录SpringBoot中如何使用外置tomcat服务器1.确保springboot项目的打包方式是war2.引入外部的tomcat依赖坐标3.把外部的tomcat服务器引入到IDEA中4.启动外部tomcat服务器5.配置tomcat服务器的访问接口SpringBoot中如何使用外置tomcat服务器1.... 查看详情

如何在springboot中使用handlermethodargumentresolver

本例子是使用HandlerMethodArgumentResolver方便的获取session中的内容。 SessionInfo.java在session中存储用户数据...publicclassSessionInfo{privateIntegeruserId;privateStringusername;privateStringua;privateStringip;...//const 查看详情

springboot中使用redissession

  springboot默认的httpsession是存在内存中。这种默认方式有几个缺点:1、当分布式部署时,存在session不一致的问题;2、当服务重启时session就会丢失,这时候用户就需要重新登陆,可能导致用户数据丢失。通常会使用redis来保存... 查看详情

springboot中commandlinerunner的使用

https://blog.csdn.net/BBQ__ZXB/article/details/126181495 查看详情

springboot中使用servlet,方法一

 首页,我也不知道什么场景下SpringBoot才会使用Servlet,有知道的可以评论告诉我,谢谢!!!一、先上完整的目录结构:二、使用SpringBoot后,就没有web.xml文件了,所以我们配置Servlet使用注解@WebServlet:MyServlet.java文件内容:... 查看详情

在springboot中使用@configurationproperties注解

...在mail.properties文件中。属性必须命名规范才能绑定成功。SpringBoot使用一些松的规则来绑定属性到@ConfigurationProperties bean并且支持分层结构(hierarchicalstructure)。开始创建一个@ConfigurationProperties bean: @Configur 查看详情

在springboot工程中使用filter

在springboot工程中使用filter一、什么是filter过滤器实际上就是用来对web资源进行拦截,做一些处理后再交给下一个过滤器或servlet处理通常都是用来拦截request进行处理的,也可以对返回的response进行拦截处理。filter可以在请求到达s... 查看详情

springboot中使用esper入门

参考技术Aesper是一个比较经典的CEP(ComplexEventProcessing)的开源实现(开源协议为GPLv2),这里简单介绍下如何在springboot中使用。在esper-6.1.0-sources.jar!/com/espertech/esper/core/service/EPServiceProviderImpl.java的构造器中也调用了初始化 查看详情

如何使用 JWT Authentication 在 springboot 中使用 html 模板?

】如何使用JWTAuthentication在springboot中使用html模板?【英文标题】:HowtousehtmltemplateinspringbootusingJWTAuthentication?【发布时间】:2020-01-3121:05:16【问题描述】:几天来,我开始学习使用springboot,尤其是使用springsecurity进行用户身份验... 查看详情

在springboot中使用https

https://www.jianshu.com/p/8d4aba3b972dhttps://www.jdon.com/49625 查看详情

springboot中使用aop做访问请求日志

springboot中使用AOP做访问请求日志:这次引入springboot的aop和日志1、pom.xml引入:<!--springBoot的aop,已经集成了springaop和AspectJ--><dependency><groupId>org.springframework.boot</groupId><artifactId>sp 查看详情

springboot中使用springsecurity

简单记录springboot中使用springsecurity作为权限安全验证框架的步骤。原理解析,连接分享。感觉写的不错记录下来https://blog.csdn.net/code__code/article/details/53885510 添加引用首先需要引入jar包,Maven坐标如下: <dependency><gro... 查看详情

在 SpringBoot 和 Angular 中使用枚举

】在SpringBoot和Angular中使用枚举【英文标题】:UsingenumswithSpringBootandAngular【发布时间】:2019-10-1717:09:07【问题描述】:我想拥有像任务重要的字段,然后使用JPA进行查询以根据任务值对其进行排序。我不知道如何正确设置mysql、s... 查看详情

在springboot中怎么使用filter

参考技术A先定义一个扩展Filter的类,然后在@Configuration文件里注入这个Bean 查看详情