spring-boot和redis的缓存使用

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: 1.运行环境开发工具:intellij ideaJDK版本:1.8项目管理工具:Maven 4.0.02.Maven Plugin管理pom.xml配置代码: 1 2 5 4.

1.运行环境

开发工具:intellij idea

JDK版本:1.8

项目管理工具:Maven 4.0.0

2.Maven Plugin管理

pom.xml配置代码:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5     <modelVersion>4.0.0</modelVersion>
 6 
 7     <groupId>com.goku</groupId>
 8     <artifactId>spring-boot-redis</artifactId>
 9     <version>1.0-SNAPSHOT</version>
10   <build>
11     <plugins>
12       <plugin>
13         <groupId>org.apache.maven.plugins</groupId>
14         <artifactId>maven-compiler-plugin</artifactId>
15         <configuration>
16           <source>1.7</source>
17           <target>1.7</target>
18         </configuration>
19       </plugin>
20     </plugins>
21   </build>
22 
23   <!-- Spring Boot 启动父依赖 -->
24   <parent>
25     <groupId>org.springframework.boot</groupId>
26     <artifactId>spring-boot-starter-parent</artifactId>
27     <version>1.5.6.RELEASE</version>
28   </parent>
29 
30   <dependencies>
31     <!-- Spring Boot web依赖 -->
32     <dependency>
33       <groupId>org.springframework.boot</groupId>
34       <artifactId>spring-boot-starter-web</artifactId>
35     </dependency>
36     <!-- Spring Boot test依赖 -->
37     <dependency>
38       <groupId>org.springframework.boot</groupId>
39       <artifactId>spring-boot-starter-test</artifactId>
40       <scope>test</scope>
41     </dependency>
42     <!-- Spring Boot redis 依赖 -->
43     <dependency>
44       <groupId>org.springframework.boot</groupId>
45       <artifactId>spring-boot-starter-data-redis</artifactId>
46     </dependency>
47   </dependencies>
48 
49 
50 </project>
View Code

3.application.properties编写

# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
View Code

4.Value序列化缓存方法编写

 1 package com.goku.demo.config;
 2 
 3 
 4 import org.springframework.core.convert.converter.Converter;
 5 import org.springframework.core.serializer.support.DeserializingConverter;
 6 import org.springframework.core.serializer.support.SerializingConverter;
 7 import org.springframework.data.redis.serializer.RedisSerializer;
 8 import org.springframework.data.redis.serializer.SerializationException;
 9 /**
10  * Created by nbfujx on 2017/11/8.
11  */
12 public class RedisObjectSerializer implements RedisSerializer<Object> {
13     private Converter<Object, byte[]> serializer = new SerializingConverter();
14     private Converter<byte[], Object> deserializer = new DeserializingConverter();
15     private static final byte[] EMPTY_ARRAY = new byte[0];
16 
17     @Override
18     public Object deserialize(byte[] bytes) {
19         if (isEmpty(bytes)) {
20             return null;
21         }
22         try {
23             return deserializer.convert(bytes);
24         } catch (Exception ex) {
25             throw new SerializationException("Cannot deserialize", ex);
26         }
27     }
28 
29     @Override
30     public byte[] serialize(Object object) {
31         if (object == null) {
32             return EMPTY_ARRAY;
33         }
34         try {
35             return serializer.convert(object);
36         } catch (Exception ex) {
37             return EMPTY_ARRAY;
38         }
39     }
40 
41     private boolean isEmpty(byte[] data) {
42         return (data == null || data.length == 0);
43     }
44 }
View Code

5.Redis缓存配置类RedisConfig编写

添加注解@EnableCaching,开启缓存功能

 1 package com.goku.demo.config;
 2 
 3 import org.springframework.cache.CacheManager;
 4 import org.springframework.cache.annotation.CachingConfigurerSupport;
 5 import org.springframework.cache.annotation.EnableCaching;
 6 import org.springframework.context.annotation.Bean;
 7 import org.springframework.context.annotation.Configuration;
 8 import org.springframework.data.redis.cache.RedisCacheManager;
 9 import org.springframework.data.redis.connection.RedisConnectionFactory;
10 import org.springframework.data.redis.core.RedisTemplate;
11 import org.springframework.data.redis.serializer.StringRedisSerializer;
12 
13 /**
14  * Created by nbfujx on 2017-12-07.
15  */
16 @SuppressWarnings("SpringJavaAutowiringInspection")
17 @Configuration
18 @EnableCaching
19 public class RedisConfig extends CachingConfigurerSupport {
20 
21     @Bean
22     public CacheManager cacheManager(RedisTemplate<Object, Object> redisTemplate) {
23         RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
24         cacheManager.setDefaultExpiration(1800);
25         return cacheManager;
26     }
27 
28     @Bean
29     public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) {
30         RedisTemplate<Object, Object> template = new RedisTemplate<>();
31         template.setConnectionFactory(factory);
32         template.setKeySerializer(new StringRedisSerializer());
33         template.setValueSerializer(new RedisObjectSerializer());
34         return template;
35     }
36 }
View Code

6.Application启动类编写

 1 package com.goku.demo;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 import org.springframework.boot.web.servlet.ServletComponentScan;
 6 
 7 /**
 8  * Created by nbfujx on 2017/11/20.
 9  */
10 // Spring Boot 应用的标识
11 @SpringBootApplication
12 @ServletComponentScan
13 public class DemoApplication {
14 
15     public static void main(String[] args) {
16         // 程序启动入口
17         // 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件
18         SpringApplication.run(DemoApplication.class,args);
19     }
20 }
View Code

7.测试用例编写

实体类User编写

 1 package test.com.goku.demo.model;
 2 
 3 import java.io.Serializable;
 4 
 5 /**
 6  * Created by nbfujx on 2017-12-07.
 7  */
 8 public class User implements Serializable {
 9 
10     private static final long serialVersionUID = -1L;
11 
12     private String username;
13     private Integer age;
14 
15     public User(String username, Integer age) {
16         this.username = username;
17         this.age = age;
18     }
19 
20     public String getUsername() {
21         return username;
22     }
23 
24     public void setUsername(String username) {
25         this.username = username;
26     }
27 
28     public Integer getAge() {
29         return age;
30     }
31 
32     public void setAge(Integer age) {
33         this.age = age;
34     }
35 }
View Code

测试方法编写,包含缓存字符实体

 1 package test.com.goku.demo;
 2 
 3 import com.goku.demo.DemoApplication;
 4 import org.junit.Test;
 5 import org.junit.runner.RunWith;
 6 import org.slf4j.Logger;
 7 import org.slf4j.LoggerFactory;
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.boot.test.context.SpringBootTest;
10 import org.springframework.data.redis.core.RedisTemplate;
11 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
12 import test.com.goku.demo.model.User;
13 
14 import java.io.Serializable;
15 
16 /**
17  * Created by nbfujx on 2017-12-07.
18  */
19 @RunWith(SpringJUnit4ClassRunner.class)
20 @SpringBootTest(classes = DemoApplication.class)
21 public class TestRedis implements Serializable{
22 
23     private final Logger logger = LoggerFactory.getLogger(getClass());
24 
25     @Autowired
26     private RedisTemplate redisTemplate;
27 
28     @Test
29     public void test() throws Exception {
30         // 保存字符串
31         redisTemplate.opsForValue().set("数字", "111");
32         this.logger.info((String) redisTemplate.opsForValue().get("数字"));
33     }
34 
35     @Test
36     public void testobject() throws Exception {
37         User user = new User("用户1", 20);
38         redisTemplate.opsForValue().set("用户1",user);
39         // 保存对象
40         User user2= (User) redisTemplate.opsForValue().get("用户1");
41         this.logger.info(String.valueOf(user2.getAge()));
42     }
43 
44 
45 }
View Code

8.查看测试结果

字符串测试

 

实体测试

 

 

9.GITHUB地址

https://github.com/nbfujx/springBoot-learn-demo/tree/master/spring-boot-redis

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
8天前
|
存储 缓存 NoSQL
【Go语言专栏】Go语言中的Redis操作与缓存应用
【4月更文挑战第30天】本文探讨了在Go语言中使用Redis进行操作和缓存应用的方法。文章介绍了Redis作为高性能键值存储系统,用于提升应用性能。推荐使用`go-redis/redis`库,示例代码展示了连接、设置、获取和删除键值对的基本操作。文章还详细阐述了缓存应用的步骤及常见缓存策略,包括缓存穿透、缓存击穿和缓存雪崩的解决方案。利用Redis和合适策略可有效优化应用性能。
|
2天前
|
存储 消息中间件 缓存
Redis缓存技术详解
【5月更文挑战第6天】Redis是一款高性能内存数据结构存储系统,常用于缓存、消息队列、分布式锁等场景。其特点包括速度快(全内存存储)、丰富数据类型、持久化、发布/订阅、主从复制和分布式锁。优化策略包括选择合适数据类型、设置过期时间、使用Pipeline、开启持久化、监控调优及使用集群。通过这些手段,Redis能为系统提供高效稳定的服务。
|
3天前
|
缓存 监控 NoSQL
Redis缓存雪崩及应对策略
缓存雪崩是分布式系统中一个常见但危险的问题,可以通过合理的缓存策略和系统设计来降低发生的概率。采用多层次的缓存架构、缓存预热、合理的缓存失效时间等措施,都可以有效应对缓存雪崩,提高系统的稳定性和性能。在实际应用中,及时发现并解决潜在的缓存雪崩问题,是保障系统可用性的关键一环。
33 14
|
6天前
|
缓存 NoSQL Java
优化Redis缓存:解决性能瓶颈和容量限制
优化Redis缓存:解决性能瓶颈和容量限制
18 0
|
6天前
|
存储 缓存 NoSQL
Redis缓存满了怎么办?
选择哪种方法取决于您的应用需求和数据访问模式。需要根据实际情况来决定如何处理Redis缓存满的情况。
29 1
|
7天前
|
XML 存储 缓存
Spring缓存是如何实现的?如何扩展使其支持过期删除功能?
总之,Spring的缓存抽象提供了一种方便的方式来实现缓存功能,并且可以与各种缓存提供商集成以支持不同的过期策略。您可以根据项目的具体需求选择适合的方式来配置和扩展Spring缓存功能。
14 0
|
7天前
|
缓存 NoSQL Java
springboot业务开发--springboot集成redis解决缓存雪崩穿透问题
该文介绍了缓存使用中可能出现的三个问题及解决方案:缓存穿透、缓存击穿和缓存雪崩。为防止缓存穿透,可校验请求数据并缓存空值;缓存击穿可采用限流、热点数据预加载或加锁策略;缓存雪崩则需避免同一时间大量缓存失效,可设置随机过期时间。文章还提及了Spring Boot中Redis缓存的配置,包括缓存null值、使用前缀和自定义过期时间,并提供了改造代码以实现缓存到期时间的个性化设置。
|
7天前
|
缓存 NoSQL 搜索推荐
Redis缓存雪崩穿透等解决方案
本文讨论了缓存使用中的三个问题:缓存穿透、缓存击穿和缓存雪崩。为解决这些问题,提出了相应策略。对于缓存穿透,建议数据校验和缓存空值;缓存击穿可采用监控扩容、服务限流或加锁机制;缓存雪崩则需避免大量缓存同时过期,可设置随机过期时间。此外,文章还介绍了Spring Boot中Redis缓存配置,包括全局设置及自定义缓存过期时间的方法。
|
8天前
|
缓存 NoSQL PHP
【PHP 开发专栏】Redis 作为 PHP 缓存的解决方案
【4月更文挑战第30天】本文探讨了Redis作为PHP缓存的优势,如高性能、丰富数据结构、数据持久化和分布式支持。通过安装配置Redis、选择PHP客户端、执行读写操作及制定缓存策略实现缓存。应用场景包括页面、数据和会话缓存。但需注意数据一致性、过期时间、容量和安全问题,以确保应用稳定和安全。Redis能有效提升PHP应用响应速度和处理能力。
|
9天前
|
存储 缓存 Java
【Spring系列笔记】依赖注入,循环依赖以及三级缓存
依赖注入: 是指通过外部配置,将依赖关系注入到对象中。依赖注入有四种主要方式:构造器注入、setter方法注入、接口注入以及注解注入。其中注解注入在开发中最为常见,因为其使用便捷以及可维护性强;构造器注入为官方推荐,可注入不可变对象以及解决循环依赖问题。本文基于依赖注入方式引出循环依赖以及三层缓存的底层原理,以及代码的实现方式。
20 0