springboot+redis实现缓存数据
在当前互联网环境下,缓存随处可见,利用缓存可以很好的提升系统性能,特别是对于查询操作,可以有效的减少数据库压力,Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件,Redis 的优势包括它的速度、支持丰富的数据类型、操作原子性,以及它的通用性。SpringBoot:一款Spring框架的子框架,也可以叫微服务框架,SpringBoot充分利用了JavaConfig的配置模式以及“约定优于配置”的理念,能够极大的简化基于SpringMVC的Web应用和REST服务开发。本篇介绍注解方式在springboot项目中使用redis做缓存。
1、在pom.xml中引入相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置redisconfig,在实际项目中可以通过配置KeyGenerator来指定缓存信息的key的生成规则
package com.example.demo; 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.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper; @Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport { @Bean
public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
RedisCacheManager rm = new RedisCacheManager(redisTemplate);
rm.setDefaultExpiration(30l);// 设置缓存时间
return rm;
} // @Bean
// public KeyGenerator myKeyGenerator(){
// return new KeyGenerator() {
// @Override
// public Object generate(Object target, Method method, Object... params) {
// StringBuilder sb = new StringBuilder();
// sb.append(target.getClass().getName());
// sb.append(method.getName());
// for (Object obj : params) {
// sb.append(obj.toString());
// }
// return sb.toString();
// }
// };
//
// } @Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
@SuppressWarnings({ "rawtypes", "unchecked" })
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
3、创建实体类
package com.example.demo;
public class User {
public User() {
}
private int id;
private String name;
private int age;
public User(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
4、service类,使用注解来做缓存
package com.example.demo; import java.util.Date; import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service; @Service
public class UserService { // @Cacheable缓存key为name的数据到缓存usercache中
@Cacheable(value = "usercache", key = "#p0")
public User findUser(String name) {
System.out.println("无缓存时执行下面代码,获取zhangsan,Time:" + new Date().getSeconds());
return new User(1, "zhangsan", 13);// 模拟从持久层获取数据
} // @CacheEvict从缓存usercache中删除key为name的数据
@CacheEvict(value = "usercache", key = "#p0")
public void removeUser(String name) {
System.out.println("删除数据" + name + ",同时清除对应的缓存");
} // @CachePut缓存新增的数据到缓存usercache中
@CachePut(value = "usercache", key = "#p0")
public User save(String name, int id) {
System.out.println("添加lisi用户");
return new User(2, "lisi", 13);
} @Cacheable(value = "usercache", key = "#p0")
public User findUser2(String name) {
System.out.println("无缓存时执行下面代码,获取lisi,Time:" + new Date().getSeconds());
return new User(2, "lisi", 13);// 模拟从持久层获取数据
}
}
5、控制器类
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
public class MyController { @Autowired
UserService userService; @GetMapping("/finduser1")
public User finduser1() {
return userService.findUser("zhangsan");
} @GetMapping("/finduser2")
public User finduser2() {
return userService.findUser2("lisi");
} @GetMapping("/adduser2")
public User adduser2() {
return userService.save("lisi", 13);
} @GetMapping("/delete")
public void removeUser() {
userService.removeUser("zhangsan");
}
}
6、配置信息,这里使用docker在本地虚拟机启动一个redis服务
spring.redis.database=0
spring.redis.host=192.168.86.133
spring.redis.password=
spring.redis.port=6379
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=100
spring.redis.pool.max-wait=-1
启动redis服务,然后启动本springboot项目,通过访问对应的url,可以看到在进行数据增删改查的时候是有缓存的。
springboot+redis实现缓存数据的更多相关文章
- spring boot 学习(十四)SpringBoot+Redis+SpringSession缓存之实战
SpringBoot + Redis +SpringSession 缓存之实战 前言 前几天,从师兄那儿了解到EhCache是进程内的缓存框架,虽然它已经提供了集群环境下的缓存同步策略,这种同步仍然需 ...
- (十五)SpringBoot之使用Redis做缓存数据
一.添加Redis依赖 <?xml version="1.0" encoding="UTF-8"?> <project xmlns=" ...
- 基于 abp vNext 和 .NET Core 开发博客项目 - 使用Redis缓存数据
上一篇文章(https://www.cnblogs.com/meowv/p/12943699.html)完成了项目的全局异常处理和日志记录. 在日志记录中使用的静态方法有人指出写法不是很优雅,遂优化一 ...
- SpringBoot + Redis:基本配置及使用
注:本篇博客SpringBoot版本为2.1.5.RELEASE,SpringBoot1.0版本有些配置不适用 一.SpringBoot 配置Redis 1.1 pom 引入spring-boot-s ...
- SpringBoot 2.x 使用Redis作为项目数据缓存
一.添加依赖 <!-- 添加缓存支持 --> <dependency> <groupId>org.springframework.boot</groupId& ...
- SpringBoot整合Redis案例缓存首页数据、缓解数据库压力
一.硬编码方式 1.场景 由于首页数据变化不是很频繁,而且首页访问量相对较大,所以我们有必要把首页数据缓存到redis中,减少数据库压力和提高访问速度. 2.RedisTemplate Jedis是R ...
- springboot mybatis redis 二级缓存
前言 什么是mybatis二级缓存? 二级缓存是多个sqlsession共享的,其作用域是mapper的同一个namespace. 即,在不同的sqlsession中,相同的namespace下,相同 ...
- SpringBoot集成Redis实现缓存处理(Spring AOP实现)
第一章 需求分析 计划在Team的开源项目里加入Redis实现缓存处理,因为业务功能已经实现了一部分,通过写Redis工具类,然后引用,改动量较大,而且不可以实现解耦合,所以想到了Spring框架的A ...
- spring-boot集成mybatis,用redis做缓存
网上有很多例子了,执行源码起码有3个,都是各种各样的小问题. 现在做了个小demo,实现spring-boot 用redis做缓存的实例,简单记录下思路,分享下源码. 缓存的实现,分担了数据库的压力, ...
随机推荐
- 使用jasmine-node 进行NodeJs单元测试 环境搭建
关于jasmine就不多说了,关于语法请参加官方文档.http://pivotal.github.io/jasmine/ 关于NodeJS的单元测试框架有多种,如果要在NodeJS中使用jasmine ...
- Alpha冲刺 - (8/10)
队名:彳艮彳亍团队 组长博客:戳我进入 作业博客:班级博客本次作业的链接 Part.2 成员汇报 组员1(组长)柯奇豪 过去两天完成了哪些任务 进一步优化代码,结合自己负责的部分修改功能 代码规范完整 ...
- 领域模型驱动设计(Domain Driven Design)入门概述 -----DDD 解释
软件开发要干什么: 反映真实世界要自动化的业务流程 解决现实问题 领域Domain Domain特指软件关注的领域 在不能充分了解业务领域的情况下是不可能做出一个好的软件 领域建模 领域模型驱动设计 ...
- elasticsearch常用JAVA API 实例
1.引入dependency <dependency> <groupId>org.springframework.data</groupId> <artifa ...
- 减少C盘空间占用的技巧
1.搜索C盘中大小大于某个值的文件:C:\Windows\SoftwareDistribution这个文件夹下很多大文件 2.搜索*.log文件 3.C:\Users\Guangshan\AppDat ...
- 零成本实现WEB性能测试(二)JMeter基础知识
特点: 支持多种服务类型进行测试,包括: Web-Http,HTTPS SOAP Database via JDBC LDAP JMS Mail-POP3 & IMAP 支持录制回放方式获取脚 ...
- Re:从零开始的Spring Security Oauth2(二)
本文开始从源码的层面,讲解一些Spring Security Oauth2的认证流程.本文较长,适合在空余时间段观看.且涉及了较多的源码,非关键性代码以…代替. 准备工作 首先开启debug信息: l ...
- C#设计模式--工厂模式之简单模式
简单工厂模式定义:简单工厂模式是属于创建型模式,又叫做静态工厂方法(Static Factory Method)模式,但不属于23种GOF设计模式之一.简单工厂模式是由一个工厂对象决定创建出哪一种产品 ...
- C#的Winform中OpenFileDialog对话框Filter属性设置包含特定字符,使用正则表达式
OpenFileDialog对话框的Filter属性说明: 首先观察Filter属性的组成部分:“Word文件|*.doc ”,前面的“Word文件”成为标签,是一个可读的字符串,可以自定定义,“|* ...
- 微信开发之c#下jssdk签名生成
参考文章 :微信JS-SDK 权限签名算法 C#版 这篇文章讲解的的比较详细,而且算法准确,但是这篇文章有几个错误的地方需要注意; url必须动态生成 url不能写死,否则就算结果和官方检测的一致,也 ...