Springboot整合Redis入门案例
整篇文章将分为6个部分以代码形式向大家展示springboot如何整合redis:
1、创建springboot项目
这个很简单,可以自行百度,这边可以参考:
https://www.cnblogs.com/little-rain/p/11063967.html
2、引入项目所需要的pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--通用池-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!--通用mapper,不需要手写sql-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
3、配置文件
application.yml文件
server:
port: 8080
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/myself?serverTimezone=UTC
username: root
password: root
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000;config.decrypt=false
main: spring.main.allow-bean-definition-overriding=true
cache:
type: ehcache
ehcache:
config: classpath:ehcache.xml
jackson:
date-format: yyyy-MM-dd HH:mm
time-zone: GMT+8
redis:
database: 0
host: 127.0.0.1
port: 6379
timeout: 1000
jedis:
pool:
max-idle: 10
min-idle: 5
max-wait: -1
#将执行的sql语句打印出来
logging:
level:
com.twq.fuse: debug
新建一个config文件,记得要在类上面加上@Configuration注解,表明其是配置文件
package com.twq.fuse.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @Description: redis配置类$
* @Date: 2021/06/23$
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String ,Object> redisTemplate(RedisConnectionFactory factory){
RedisTemplate<String ,Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
//指定Key、value的序列化方式
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
// redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setKeySerializer(new StringRedisSerializer());
return redisTemplate;
}
}
4. 业务实现
1、简单的key-value插入、查询
controller层代码
package com.twq.fuse.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.xml.ws.Action;
/**
* @Description: redis控制类$
* @Date: 2021/06/23$
*/
@RestController
public class RedisController {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping("/redis/get/{key}")
public Object get(@PathVariable("key") String key){
return redisTemplate.opsForValue().get(key);
}
@PostMapping("/redis/set/{key}/{value}")
public Object set(@PathVariable("key") String key,
@PathVariable("value") String value){
redisTemplate.opsForValue().set(key,value);
return "set success";
}
}
执行set接口
我们可以在redis的可视化工具中看到我们设置的键值对插入到缓存当中了(我这里使用的工具是Redis Desttop Manager)
执行get接口
2、稍微复杂点的业务查询
service层:
@Override
public Object getUserById(Integer id) {
//从缓存中获取数据,
String key = "user:"+id;
Object userObj = redisTemplate.opsForValue().get(key);
if (userObj == null){
//如果没有数据,则先查询数据库,并将数据设置到缓存
synchronized (this.getClass()){
userObj = redisTemplate.opsForValue().get(key);
if (userObj == null){
log.debug("-------->查询数据库");
User user = userMapper.getUserInfoById(id);
//opsForValue代表redis的string数据结构
redisTemplate.opsForValue().set(key,user);
return user;
}else {
//如果有数据直接返回
log.debug("-------->查询缓存(同步代码块)");
return userObj;
}
}
}else {
log.debug("-------->查询缓存");
}
return userObj;
}
controller层:
/**
* 根据id查询用户(从redis缓存当中查询)
* @param id
* @return
*/
@GetMapping("/getUserById/{id}")
public Object getUserById(@PathVariable("id") Integer id){
//创建线程池,模拟500个用户同时发起请求(并发)
ExecutorService es = Executors.newFixedThreadPool(200);
for (int i=0;i<500;i++){
es.submit(new Runnable() {
@Override
public void run() {
userService.getUserById(id);
}
});
}
return userService.getUserById(id);
}
6. 测试
首先需要打开你本地的redis服务,然后再启动项目,可以直接再浏览器或者使用postman等工具执行相关接口,(http://localhost:8080/getUserById/2)
可以在控制台看到第一次查询是在数据库中查到的,都是第二次查询以后都是在redis缓存中查询的
这是我边看学习视频边写的一个小案例,自己感觉挺受用的,适合没接触过redis的小白,所有想分享给大家,需要对大家有一定的帮助