SpringBoot2.0使用redis作数据缓存


使用工具

  • IntelliJ IDEA 2018.1 x64
  • jdk8
  • SpringBoot 2.0.3

步骤

首先,先创建一个SpringBoot项目,在pom.xml里面添加以下依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 <!--添加redis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--添加sprng-data-jpa依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--添加mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

为了区分我们是从redis中获取的数据,这里引入mysql来从数据库中查询,接下来在application配置文件中加入数据库连接

1
2
3
4
5
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=XXX
spring.datasource.password=XXX
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/XXX?characterEncoding=utf8
spring.jpa.show-sql=true

这里redis如果没有配置的话就是默认的,地址为127.0.0.1,端口号为6379,密码为空。接着创建实体类

1
2
3
4
5
6
7
8
9
@Entity
@Table(name = "user")
public class UserBean implements Serializable {
@Id
@GeneratedValue
private Long id;
private String username;
private String password;
--省略setter、getter方法

dao层

1
2
public interface UserJpa extends JpaRepository<UserBean,Long> {
}

这里继承SpringDataJpa的JpaRepository,可以实现基础的增删改查操作,具体更多以用法后面会写一些,以上基本配置完成之后,重要部分来了,创建service

1
2
3
4
5
6
public interface RedisService {
/**
* 测试取出缓存数据
*/
String getRedisData();
}

serviceImpl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Service
public class RedisServiceImpl implements RedisService {

private static final Logger logger =LoggerFactory.getLogger(RedisServiceImpl.class);

@Autowired
private StringRedisTemplate redisTemplate;

@Autowired
private UserJpa userJpa;

@Override
public String getRedisData() {
ValueOperations<String, String> ops = redisTemplate.opsForValue();
String redisData = ops.get("redisData");
// 缓存中没有数据
if (redisData == null){
logger.info("查询数据库,存入缓存数据");
// 查询数据库
List<UserBean> userList = userJpa.findAll();
// 存入缓存
ops.set("redisData",userList.toString(),1800,TimeUnit.SECONDS);
return userList.toString();
}
logger.info("直接从缓存中获取数据");
return redisData;
}
}

一般时先从redis里面去数据,如果没有取到数据的话,就去查数据库,当然,查到数据之后也应该放进redis中,方便下次取出。这里ops.set()方法表示存入key为redisData的userList数据,设置有效时间为1800,TimeUnit.seconds表示单位为秒。
最后,创建测试类测试一下

1
2
3
4
5
6
7
8
9
10
11
12
@RunWith(SpringRunner.class)
@SpringBootTest
public class QuartzApplicationTests {
@Autowired
private RedisService redisService;

@Test
public void contextLoads() {
String redisData = redisService.getRedisData();
System.out.println(redisData);
}
}

启动测试类观察控制台的打印日志:

第一次启动,因为redis里面没有数据,所以查询数据库,然后放到redis里面,再次启动测试类

这里看到日志里已经没有取查我们的数据库了,而是直接从redis里面拿的数据了,大功告成 ^-^

-------------本文结束感谢您的阅读-------------