1.运行环境

开发工具:intellij idea

JDK版本:1.8

项目管理工具:Maven 4.0.0

2.Maven Plugin管理

pom.xml配置代码:

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.goku</groupId>
<artifactId>spring-boot-redis</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build> <!-- Spring Boot 启动父依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent> <dependencies>
<!-- Spring Boot web依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot test依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Boot redis 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies> </project>

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

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

 package com.goku.demo.config;

 import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
/**
* Created by nbfujx on 2017/11/8.
*/
public class RedisObjectSerializer implements RedisSerializer<Object> {
private Converter<Object, byte[]> serializer = new SerializingConverter();
private Converter<byte[], Object> deserializer = new DeserializingConverter();
private static final byte[] EMPTY_ARRAY = new byte[0]; @Override
public Object deserialize(byte[] bytes) {
if (isEmpty(bytes)) {
return null;
}
try {
return deserializer.convert(bytes);
} catch (Exception ex) {
throw new SerializationException("Cannot deserialize", ex);
}
} @Override
public byte[] serialize(Object object) {
if (object == null) {
return EMPTY_ARRAY;
}
try {
return serializer.convert(object);
} catch (Exception ex) {
return EMPTY_ARRAY;
}
} private boolean isEmpty(byte[] data) {
return (data == null || data.length == 0);
}
}

5.Redis缓存配置类RedisConfig编写

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

 package com.goku.demo.config;

 import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer; /**
* Created by nbfujx on 2017-12-07.
*/
@SuppressWarnings("SpringJavaAutowiringInspection")
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport { @Bean
public CacheManager cacheManager(RedisTemplate<Object, Object> redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
cacheManager.setDefaultExpiration(1800);
return cacheManager;
} @Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new RedisObjectSerializer());
return template;
}
}

6.Application启动类编写

 package com.goku.demo;

 import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan; /**
* Created by nbfujx on 2017/11/20.
*/
// Spring Boot 应用的标识
@SpringBootApplication
@ServletComponentScan
public class DemoApplication { public static void main(String[] args) {
// 程序启动入口
// 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件
SpringApplication.run(DemoApplication.class,args);
}
}

7.测试用例编写

实体类User编写

 package test.com.goku.demo.model;

 import java.io.Serializable;

 /**
* Created by nbfujx on 2017-12-07.
*/
public class User implements Serializable { private static final long serialVersionUID = -1L; private String username;
private Integer age; public User(String username, Integer age) {
this.username = username;
this.age = age;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
}
}

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

 package test.com.goku.demo;

 import com.goku.demo.DemoApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import test.com.goku.demo.model.User; import java.io.Serializable; /**
* Created by nbfujx on 2017-12-07.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class TestRedis implements Serializable{ private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired
private RedisTemplate redisTemplate; @Test
public void test() throws Exception {
// 保存字符串
redisTemplate.opsForValue().set("数字", "111");
this.logger.info((String) redisTemplate.opsForValue().get("数字"));
} @Test
public void testobject() throws Exception {
User user = new User("用户1", 20);
redisTemplate.opsForValue().set("用户1",user);
// 保存对象
User user2= (User) redisTemplate.opsForValue().get("用户1");
this.logger.info(String.valueOf(user2.getAge()));
} }

8.查看测试结果

字符串测试

实体测试

9.GITHUB地址

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

spring-boot和redis的缓存使用的更多相关文章

  1. Spring Boot + Mybatis + Redis二级缓存开发指南

    Spring Boot + Mybatis + Redis二级缓存开发指南 背景 Spring-Boot因其提供了各种开箱即用的插件,使得它成为了当今最为主流的Java Web开发框架之一.Mybat ...

  2. (35)Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】

    [本文章是否对你有用以及是否有好的建议,请留言] 本文章牵涉到的技术点比较多:Spring Data JPA.Redis.Spring MVC,Spirng Cache,所以在看这篇文章的时候,需要对 ...

  3. Spring Boot 集成 Redis 实现缓存机制

    本文章牵涉到的技术点比较多:spring Data JPA.Redis.Spring MVC,Spirng Cache,所以在看这篇文章的时候,需要对以上这些技术点有一定的了解或者也可以先看看这篇文章 ...

  4. Spring Boot 整合 Redis 实现缓存操作

    摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢!   『 产品没有价值,开发团队再优秀也无济于事 – <启示录> 』   本文提纲 ...

  5. Spring Boot 整合Redis 实现缓存

      本文提纲 一.缓存的应用场景 二.更新缓存的策略 三.运行 springboot-mybatis-redis 工程案例 四.springboot-mybatis-redis 工程代码配置详解   ...

  6. Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】

    转自:https://blog.csdn.net/linxingliang/article/details/52263763 spring boot 自学笔记(三) Redis集成—RedisTemp ...

  7. spring boot从redis取缓存发生java.lang.ClassCastException异常

    目录树 异常日志信息 错误原因 解决方法 异常日志信息 2018-09-24 15:26:03.406 ERROR 13704 --- [nio-8888-exec-8] o.a.c.c.C.[.[. ...

  8. (37)Spring Boot集成EHCache实现缓存机制【从零开始学Spring Boot】

    [本文章是否对你有用以及是否有好的建议,请留言] 写后感:博主写这么一系列文章也不容易啊,请评论支持下. 如果看过我之前(35)的文章这一篇的文章就会很简单,没有什么挑战性了. 那么我们先说说这一篇文 ...

  9. Spring Boot 结合 Redis 缓存

    Redis官网: 中:http://www.redis.cn/ 外:https://redis.io/ redis下载和安装 Redis官方并没有提供Redis的Windows版本,这里使用微软提供的 ...

  10. Spring Boot自定义Redis缓存配置,保存value格式JSON字符串

    Spring Boot自定义Redis缓存,保存格式JSON字符串 部分内容转自 https://blog.csdn.net/caojidasabi/article/details/83059642 ...

随机推荐

  1. jdbc odbc JDBC-ODBC

    https://zh.wikipedia.org/zh-cn/ODBC ODBC(Open Database Connectivity,开放数据库互连)提供了一种标准的API(应用程序编程接口)方法来 ...

  2. 使用Flask+nginx+uwsgi+Docker部署python应用

    https://www.cnblogs.com/vh-pg/p/11731637.html

  3. 用notepad++ 打造轻量级Java编译器

    http://blog.163.com/jackie_howe/blog/static/19949134720125591752396/ 用notepad++ 打造轻量级Java编译器 2012-06 ...

  4. 全文搜索 ElasticSearch

    今天突然想了解一下ES,看看有什么优势,能不能用在项目中. 说到ES就不得不了解它的底层技术-全文检索 Ref: 全文检索的基本原理 https://blog.csdn.net/wangmaohong ...

  5. Convolutional Neural Networks(1): Architecture

    Concolutional Neural Networks(CNN)同样使用三层结构,但结构上同Feedforward Neural Network有很大不同,其结构如下图: Input layer: ...

  6. 结合Pool进程池进程,实现进程之间的通讯,稍微复杂的运用

    #进程池中的Queue """ 如果要用Pool创建进程,就需要multiprocessing.Manager()中的Queue() 而不是multiprocessing ...

  7. vuex基本使用

    1.组件之间共享数据的方式 父向子传值:v-bind 属性绑定 子向父传值:v-on 事件绑定 兄弟组件之间共享数据:EventBus $on 接收数据的那个组件 $emit 发送数据的那个组件 2. ...

  8. deepFreeze

    obj1 = {   internal: {} }; Object.freeze(obj1); obj1.internal.a = 'aValue'; obj1.internal.a // 'aVal ...

  9. HTML批量修改——正则表达式实践

    目录 1.问题描述 2.初步研究 3.进一步研究 3.1提取2.*中的序号* 3.2提取标题 3.3选取全文 3.4替换 参考资料 1.问题描述 如下所示的一段HTML代码: ... <h2 a ...

  10. Codeforces - 1194C - From S To T - 子序列 - 排序

    https://codeforces.com/contest/1194/problem/C 好像没什么好说的,要能构造s必须是t的子序列,并且相差的字符集合d是p的子集. 用双指针法求两遍子序列就可以 ...