博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring-boot和redis的缓存使用
阅读量:7083 次
发布时间:2019-06-28

本文共 7848 字,大约阅读时间需要 26 分钟。

1.运行环境

开发工具:intellij idea

JDK版本:1.8

项目管理工具:Maven 4.0.0

2.Maven Plugin管理

pom.xml配置代码:

1 
2
5
4.0.0
6 7
com.goku
8
spring-boot-redis
9
1.0-SNAPSHOT
10
11
12
13
org.apache.maven.plugins
14
maven-compiler-plugin
15
16
1.717
1.7
18
19
20
21
22 23
24
25
org.springframework.boot
26
spring-boot-starter-parent
27
1.5.6.RELEASE
28
29 30
31
32
33
org.springframework.boot
34
spring-boot-starter-web
35
36
37
38
org.springframework.boot
39
spring-boot-starter-test
40
test
41
42
43
44
org.springframework.boot
45
spring-boot-starter-data-redis
46
47
48 49 50
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 {13     private Converter
serializer = new SerializingConverter();14 private Converter
deserializer = new DeserializingConverter();15 private static final byte[] EMPTY_ARRAY = new byte[0];16 17 @Override18 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 @Override30 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 @Configuration18 @EnableCaching19 public class RedisConfig extends CachingConfigurerSupport {20 21     @Bean22     public CacheManager cacheManager(RedisTemplate
redisTemplate) {23 RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);24 cacheManager.setDefaultExpiration(1800);25 return cacheManager;26 }27 28 @Bean29 public RedisTemplate
redisTemplate(RedisConnectionFactory factory) {30 RedisTemplate
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 @SpringBootApplication12 @ServletComponentScan13 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     @Autowired26     private RedisTemplate redisTemplate;27 28     @Test29     public void test() throws Exception {30         // 保存字符串31         redisTemplate.opsForValue().set("数字", "111");32         this.logger.info((String) redisTemplate.opsForValue().get("数字"));33     }34 35     @Test36     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地址

转载地址:http://etmml.baihongyu.com/

你可能感兴趣的文章
react js踩坑之路(一)
查看>>
django项目设计
查看>>
[iOS]如何给Label或者TextView赋HTML数据
查看>>
C# To IL(四)
查看>>
监听时间变动事件Intent.ACTION_TIME_TICK
查看>>
MarkChanges: Jmeter
查看>>
Data truncation: Incorrect datetime value: 'May 15, 2019 4:15:37 PM
查看>>
JS Date.Format
查看>>
程序员的十大经验和教训
查看>>
数据生成树 ---新增
查看>>
#if和#ifdef区别
查看>>
cpu故障定位 top strace pstack
查看>>
[转] 多进程 join && daemon
查看>>
centos下将系统预置yum源更换为阿里云源
查看>>
Shell.Users 提权
查看>>
Spring通过注解注入有参
查看>>
HttpServletRequest应用(转)
查看>>
java.lang.ClassNotFoundException: org.apache.juli.logging.LogFactory的解决办法
查看>>
NGUI类关系图
查看>>
【java集合框架源码剖析系列】java源码剖析之HashSet
查看>>