Spring应用开发——Spring Boot与Redis的集成(二)
Redis是一个完全开源免费的,遵守BSD协议的、内存中的数据结构存储,它既可以作为数据库,也可以作为缓存和消息代理。因其性能优异等优势,目前已被很多企业所使用,但通常在企业中我们会将其作为缓存来使用。Spring Boot对redis也提供了自动配置的支持,接下来讲解如何在Spring Boot使用Redis。
1、添加Redis起步依赖
在pom.xml中添加Spring Boot支持Redis的依赖配置,具体如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.4.RELEASE</version>
</dependency>
2、添加缓存注解
(1)在引导类(Demo)Application.java中,添加@EnableCaching注解开启缓存,添加后的代码如下所示:
注:后期调试时将DemoApplication.java改为application.java
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
(2)在业务逻辑类UserServiceImpl的getAllUsers()方法上添加@Cacheable注解来支持缓存,添加后的实现代码如下:
//查询所有用户
@Override
@Cacheable(value="UserCache",key="'user.getAllUsers'")
public List<User> getAllUsers(){
return this.userMapper.getAllUsers();
}
3、使实体类实现可序列化接口
为了便于数据的传输,需要将实体类User实现序列化接口Serializable,具体代码如下:
package com.itheima.springboot.po;
import java.io.Serializable;
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1664137510764351595L;
private Integer id;
private String username;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public User() {
super();
}
public User(Integer id, String username, String address) {
super();
this.id = id;
this.username = username;
this.address = address;
}
}
4、指定Redis缓存主机地址
通常情况下,redis缓存与web应用并非部署在一台机器上,此时就需要远程调用Redis。在application.yml中添加指定Redis所在主机及其端口号的配置,具体如下:
#DB Configuration
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/microservice
username: root
password: root
redis:
host: 192.168.10.11
port: 6379
activemq:
broker-url: tcp://192.168.10.11:61616
#logging
logging:
level:
com.itheima.springboot: debug
5、启动项目,测试缓存使用
在远程主机中启动Redis服务,并启动本地项目,在浏览器地址栏中输入访问地址http://localhost:8080/user.html后,eclipse控制台中显示如下信息:
6、清除Redis缓存
Redis中的缓存数据不会一直都存在,当执行添加、更新和删除操作后,数据库中的数据会发生变化,而Redis缓存中的数据同样也需要进行相应的变化。为了保证Redis缓存中的数据与数据库中的一致,通常需要在执行添加、更新和删除操作之前清除缓存,然后在下一次执行查询操作时,将新的数据存储到Redis缓存中。
实现清除缓存的功能只需在相应方法中使用@CacheEvict注解即可。以删除用户为例,在业务逻辑类UserServiceImpl.java中的deleteUser()方法上添加@CacheEvict注解信息,具体如下:
//删除用户
@Override
@CacheEvict(value="UserCache",key="'user.getAllUsers'")
public void deleteUser(Integer id) {
System.out.println("删除了id为"+id+"的用户");
this.userMapper.delete(id);
}
}
从上述代码中可以看出,@CacheEvict注解的属性配置与@Cacheable注解的配置完全相同。
启动项目后,在浏览器输入地址http://localhost:8080/user/delete/1即可执行项目中的删除操作。删除后,Eclipse控制台会显示出输出语句信息,同时Redis中的缓存数据也会被相应删除。