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. php的URL查询字符串解析函数

    URL查询字符串格式:Data[650][BLN]=40002307312&Data[650][Status]=電聯無人接聽. 解析这种数据使用函数:parse_str(). parse_st ...

  2. openpyxl模块简单入门

    一.openpyxl简介和安装 python 读写 excel 有好多选择,但是,方便操作的库不多,在我尝试了几个库之后,我觉得两个比较方便的库分别是 xlrd/xlwt.openpyxl. 之所以推 ...

  3. Mac环境搭建nginx服务器

    一 安装 1 安装Homebrew macOS 缺失的软件包的管理器,安装方法参考官网.(可能被墙) 2 安装nginx. brew install nginx 先更新homebrew.再安装ngin ...

  4. excel wps access mysql数据表格的查询之路

    简直血崩,最近去做兼职,每天都有大量的表格数据要整理. 开始 还是 用 excel的用起来还算顺畅,慢慢慢慢的发现了各种弊端.大概类似于分组排序什么什么的好多啦~~~不过也确实是用了不到两个小时就能比 ...

  5. 【python】含中文字符串截断

    对于含多字节的字符串,进行截断的时候,要判断截断处是几字节字符,不能将多字节从中分割,避免截断后乱码 下面给出utf8和gb18030上的实现, 用任何一种都可以,可以先进行转码,用encode, d ...

  6. Mac009--Axure RP安装

    Mac--Axure RP安装 一.下载Axure RP8.0 下载网址:https://www.axure.com/download  (下载mac版本) Axure RP说明: Axure RP是 ...

  7. oracle--用户区别sys和system

    1.数据库的启动需要以SYSDBA/SYSOPER身份登录. 2.如果在同一主机上使用IPC连接到数据库使用操作系统授权,登录任何一个用户都可以拥有as sysdba和as sysoper. 3.sy ...

  8. rm 删除文件太多

    在工程环境下,一个文件夹包含有100多万个文件,这时用命令去删除这些文件: rm -rf * 会出现报错如下: /bin/rm: cannot execute [Argument list too l ...

  9. bfs(标记整个棋盘)

    1004 四子连棋 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 黄金 Gold       题目描述 Description 在一个4*4的棋盘上摆放了14颗棋子,其中有7颗白色 ...

  10. Windows程序设计(七)--鼠标

    7.2 客户区鼠标消息 当鼠标移过窗口的显示区域时,窗口消息处理程序收到WM_MOUSEMOVE消息.当在窗口的显示区域中按下或者释放一个鼠标按键时,窗口消息处理程序会接收到下面这些消息: 键 按下 ...