关键词:
Spring Boot 集成 Redis 缓存
在此章,我们将 SpringBoot 集成 Redis 缓存,Redis是一个开源的,基于内存的数据结构存储,可以用作数据库、缓存和消息代理,在本章仅讲解缓存集成。
准备工作
当前项目工具及环境
- 开发工具 IDEA 2020.3
- 依赖管理 Maven
- Spring Boot
- JDK 1.8
- Redis
现在去初始化一个Spring网站初始生成一个SpringBoot项目
新建项目
点击 Next 后设置项目名称后,点击 Finish 完成创建项目
新建实体对象
要将数据存到redis,我们需要定义一个实体来进行交互,并需要序列化实体对象
User.java
package com.github.gleans.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import javax.persistence.*;
import java.io.Serializable;
@Data
@Entity
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "SEQ_GEN", sequenceName = "SEQ_USER", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_GEN")
private Long id;
private String name;
private long money;
使用JPA的简洁数据操作
UserRepository.java
package com.github.gleans.dao;
import com.github.gleans.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* 操作数据库
*/
@Repository
public interface UserRepository extends JpaRepository<User, Long>
接口api代码
UserController.java
import com.github.gleans.dao.UserRepository;
import com.github.gleans.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Slf4j
@RestController
public class UserController
private UserRepository userRepository;
@Autowired
public void setUserRepository(UserRepository userRepository)
this.userRepository = userRepository;
@Cacheable(cacheNames = "userAll")
@GetMapping("user/all")
public Object getUserAll()
return userRepository.findAll();
@Cacheable(value = "users", key = "#userId", unless = "#result.money < 10000")
@GetMapping("user/con/userId")
public Object getUserByCondition(@PathVariable Long userId)
return userRepository.findById(userId);
@CachePut(value = "users", key = "#user.id")
@PutMapping("/update")
public User updatePersonByID(@RequestBody User user)
userRepository.save(user);
return user;
@CacheEvict(value = "users", allEntries=true)
@DeleteMapping("/id")
public void deleteUserByID(@PathVariable Long id)
List<User> userListOld = userRepository.findAll();
log.info("删除前:", userListOld.toString());
userRepository.deleteById(id);
List<User> userList = userRepository.findAll();
log.info("删除后:", userList.toString());
配置 application.yml
# Redis Config
spring:
datasource:
url: jdbc:h2:mem:activiti;DB_CLOSE_DELAY=1000
driverClassName: org.h2.Driver
username: root
password: root
cache:
type: redis
redis:
host: localhost
port: 6379
password: ekko1234
jpa:
show-sql: true
启动 Redis
项目根目录, 使用docker-compose up -d
启动 redis
Microsoft Windows [版本 10.0.17763.1339]
(c) 2018 Microsoft Corporation。保留所有权利。
C:\\Users\\ekko\\Documents\\SpringBootLearn>cd springboot-redis
C:\\Users\\ekko\\Documents\\SpringBootLearn\\springboot-redis>docker-compose up -d
Creating network "springboot-redis_default" with the default driver
Creating my_redis ... done
C:\\Users\\ekko\\Documents\\SpringBootLearn\\springboot-redis>
开启缓存并初始化数据
在启动类增加注解@EnableCaching
开启缓存
并实现CommandLineRunner接口来执行启动完成之后的任务
SpringBootRedisApplication.java
import com.github.gleans.dao.UserRepository;
import com.github.gleans.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@Slf4j
//springboot启动时执行任务CommandLineRunner
@SpringBootApplication
//开启缓存
@EnableCaching
public class SpringBootRedisApplication implements CommandLineRunner
private UserRepository userRepository;
public static void main(String[] args)
SpringApplication.run(SpringBootRedisApplication.class, args);
@Autowired
public void setUserRepository(UserRepository userRepository)
this.userRepository = userRepository;
@Override
public void run(String... args) throws Exception
log.info("开始初始化user ->user count ->", userRepository.count());
User james = new User(1L, "James", 2000);
User potter = new User(2L, "Potter", 4000);
User dumbledore = new User(3L, "Dumbledore", 999999);
userRepository.save(james);
userRepository.save(potter);
userRepository.save(dumbledore);
log.info("初始化完成 数据-> .", userRepository.findAll());
新增缓存
当我们数据库查询出来的值要放到缓存里,用@Cacheable
注解
@Cacheable(value = "users", key = "#userId", unless = "#result.money < 10000")
@RequestMapping(value = "/userId", method = RequestMethod.GET)
public Object getUser(@PathVariable Long userId)
logger.info("获取user信息根据ID-> .", userId);
return userRepository.findById(userId);
我们访问 localhost:8080/1 和 localhost:8080/3 分别两次
发现id为3的就走了一次方法 说明缓存成功
id为1的走了两次是因为 unless里条件成立就不会缓存到redis
更新缓存
每次当我们的数据库的值要更改,我们缓存的也要更改 ,我们可以使用 @CachePut 注解
@CachePut(value = "users", key = "#user.id")
@PutMapping("/update")
public User updatePersonByID(@RequestBody User user)
userRepository.save(user);
return user;
删除缓存
当我们的数据从数据库删除,我们也要从缓存进行删除,我们可以使用 @CacheEvict
注解
allEntries 是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存
@CacheEvict(value = "users", allEntries=true)
@DeleteMapping("/id")
public void deleteUserByID(@PathVariable Long id)
logger.info("删除用户根据ID-> ", id);
userRepository.deleteById(id);
在redis中查看已经没有了缓存
redis可视化工具下载地址在github
有
源码地址
https://github.com/Gleans/SpringBootLearn/tree/master/springboot-redis
逻辑脑图
springboot2.x:springboot集成redis
Redis简介什么是RedisRedis是目前使用的非常广泛的免费开源内存数据库,是一个高性能的key-value数据库。Redis与其他key-value缓存(如Memcached)相比有以下三个特点:1.Redis支持数据的持久化,它可以将内存中的数据保存在磁盘中,重... 查看详情
springboot2.x集成单节点redis
Springboot2.x集成单节点Redis说明在Springboot1.x版本中,默认使用Jedis客户端来操作Redis,而在Springboot2.x版本中,默认使用Lettuce客户端来操作Redis。Springboot提供了RedisTemplate来统一封装了对Redis操作,开发者只需要使用RedisTemplate就可以... 查看详情
springboot2.x集成redis哨兵模式
Springboot2.x集成Redis哨兵模式说明Redis哨兵模式是Redis高可用方案的一种实现方式,通过哨兵来自动实现故障转移,从而保证高可用。准备条件pom.xml中引入相关jar<!--集成Redis--><dependency><groupId>org.springframework.boot</group... 查看详情
springboot2.x基础教程:使用集中式缓存redis
之前我们介绍了两种进程内缓存的用法,包括SpringBoot默认使用的ConcurrentMap缓存以及缓存框架EhCache。虽然EhCache已经能够适用很多应用场景,但是由于EhCache是进程内的缓存框架,在集群模式下时,各应用服务器之间的缓存都是独... 查看详情
springboot集成redis(代码片段)
springboot整合Redisredis学习笔记狂神视频SpringBoot操作数据:spring-datajpajdbcmongodbredis!SpringData也是和SpringBoot齐名的项目!说明:在SpringBoot2.x之后,原来使用的jedis被替换为了lettucejedis:采用的直连 查看详情
springboot2.x集成knife4j(代码片段)
...。如何使用knife4j?简略的说一下,基础环境搭建可参考:SpringBoot2.x集成Swagger2这里我说一下主要配置区别:环境说明:新增knife4j.version:2.0.21.导入pom依赖<dependency& 查看详情
springboot2.x集成dozer(代码片段)
Dozer是JavaBean到JavaBean的映射器,它以递归的方式将数据从一个对象复制到另一个对象。通常,这些JavaBean将具有不同的复杂类型。它支持简单属性映射,复杂类型映射,双向映射,隐式显式映射,以及递归... 查看详情
springboot集成redis实现缓存(代码片段)
前言在此章,我们将SpringBoot集成Redis缓存,Redis是一个开源的,基于内存的数据结构存储,可以用作数据库、缓存和消息代理,在本章仅讲解缓存集成。一键获取源码地址准备工作当前项目工具及环境开发工具... 查看详情
springboot集成redis实现缓存(代码片段)
前言在此章,我们将SpringBoot集成Redis缓存,Redis是一个开源的,基于内存的数据结构存储,可以用作数据库、缓存和消息代理,在本章仅讲解缓存集成。一键获取源码地址准备工作当前项目工具及环境开发工具... 查看详情
springboot2.x集成antisamy防御xss攻击(代码片段)
AntiSamy是OWASP的一个开源项目,通过对用户输入的HTML、CSS、JavaScript等内容进行检验和清理,确保输入符合应用规范。AntiSamy被广泛应用于Web服务对存储型和反射型XSS的防御中。XSS攻击全称为跨站脚本攻击(CrossSiteScripti... 查看详情
springboot集成redis配置mybatis二级缓存(代码片段)
...获取一、MyBatis缓存机制1.1、一级缓存1.2、二级缓存二、集成Redis2.1、安装Redis2.2、项目引入Redis2.2.1、Maven依赖2.2.2、配置application.yml2.2.3、配置序列化规则三、配置二级缓存2.1、开启二级缓存2.2、自定义缓存类2.3、增加注解2.4、测... 查看详情
springboot2.x集成elasticsearch5.x实战增删改查
...spring-data没有对应的5.x版本,出于对方面考虑,所以就用springboot2.x来做一个demo,分享出来。如果有错误,欢迎指出。具体的代码网址githup:https://github.com/growu 查看详情
最全springboot2.x系列config配置集成篇-1参数配置(代码片段)
文章目录前言一、两种配置文件1、加载顺序上的区别2、应用场景二、不同环境配置文件三、读取配置文件信息1、@Value注解读取文件2、Environment读取文件3、@ConfigurationProperties读取配置文件总结前言使用过SpringBoot的小伙伴... 查看详情
最全springboot2.x系列config配置集成篇-1参数配置(代码片段)
文章目录前言一、两种配置文件1、加载顺序上的区别2、应用场景二、不同环境配置文件三、读取配置文件信息1、@Value注解读取文件2、Environment读取文件3、@ConfigurationProperties读取配置文件总结前言使用过SpringBoot的小伙伴... 查看详情
springboot2.x集成rabbirmq延迟交换机报错unknownexchangetype‘x-delayed-message‘找不到队列(代码片段)
确定是否安装延迟交换机插件rabbitmq_delayed_message_exchange windows环境 RabbitMQ3.9.13 Erlang24.3.2****************************************************************************************************window 查看详情
springboot2.x系列教程(七十)springbootactuator集成及自定义endpoint详解
前言曾经看到SpringBootActuator这个框架时,一直在想,它到底有什么作用呢?虽然知道它提供了很多端点,有助于应用程序的监控和管理,但如果没有直接的实践案例,还是很难有说服力的。直到上篇文章《微服务架构:Nacos本地... 查看详情
springboot2.x实践记:@springboottest(代码片段)
目录@SpringBootTest用@SpringBootTest集成测试用@SpringBootTest单元测试小结TL;DR在SpringBoot中做测试,默认使用@SpringBootTest注解,今天我们就来快速学习如何进行单元测试或集成测试。1.@SpringBootTest运行SprngBoot测试... 查看详情
springboot2.x实践记:@springboottest(代码片段)
目录@SpringBootTest用@SpringBootTest集成测试用@SpringBootTest单元测试小结TL;DR在SpringBoot中做测试,默认使用@SpringBootTest注解,今天我们就来快速学习如何进行单元测试或集成测试。1.@SpringBootTest运行SprngBoot测试... 查看详情