springboot整合redis(数据库演示)
redis配置文件RedisConfig
接下来在 config
包下创建一个 Redis 配置类 RedisConfig
,在配置类上加入注解 @Configuration
,注入一个 CacheManager
来配置一些相关信息
/**
* <p>
* redis配置
* </p>
*
*/
@Configuration
@EnableCaching
public class RedisConfig {
/**
* 默认情况下的模板只能支持RedisTemplate<String, String>,也就是只能存入字符串,因此支持序列化
*/
@Bean
public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Serializable> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
/**
* 配置使用注解的时候缓存配置,默认是序列化反序列化的形式,加上此配置则为 json 形式
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
// 配置序列化
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
RedisCacheConfiguration redisCacheConfiguration = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(factory).cacheDefaults(redisCacheConfiguration).build();
}
}
数据对象
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
private static final long serialVersionUID = 701066726681770595L;
private String name;
private Long id;
private String sex;
private String describe;
}
mapper层(采用了mybatis plus)
@Mapper
@Repository
public interface StudyMapper extends BaseMapper<User> {
}
Service层
public interface StudyService extends IService<User>{
/**
* 保存或修改用户
*
* @param user 用户对象
* @return 操作结果
*/
User saveorUpdate(User user);
/**
* 获取用户
*
* @param id key值
* @return 返回结果
*/
User get(Long id);
/**
* 删除
*
* @param id key值
*/
void delete(Long id);
}
在这里说下这几个注解:
@CacheConfig 类级别的缓存注解,允许共享缓存名称
@Cacheable 触发缓存入口
Spring在每次执行前都会检查Cache中是否存在相同key的缓存元素,如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回,否则才会执行方法并将返回结果存入指定的缓存中
一般用于查询操作,根据 key 查询缓存.
- 如果 key 不存在,查询 db,方法返回的结果更新到缓存中。
- 如果 key 存在,直接查询缓存中的数据。
@CacheEvict 触发移除缓存
根据 key 删除缓存中的数据。
@CacahePut 更新缓存
@CachePut也可以声明一个方法支持缓存功能。与@Cacheable不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中
一般用于更新和插入操作中
@Slf4j
@Service("studyService")
public class StudyServiceImpl extends ServiceImpl<StudyMapper, User> implements StudyService {
@Resource
private StudyMapper studyMapper;
/**
* 保存或修改用户
*
* @param user 用户对象
* @return 操作结果
*/
@CachePut(value = "user", key = "#user.id")
@Override
public User saveorUpdate(User user) {
log.info("保存用户【user】= {}", user);
studyMapper.insert(user);
return user;
}
/**
* 获取用户
*
* @param id key值
* @return 返回结果
*/
@Cacheable(value = "user", key = "#id")
@Override
public User get(Long id) {
// 我们假设从数据库读取
log.info("查询用户【id】= {}", id);
return studyMapper.selectById(id);
}
/**
* 删除
*
* @param id key值
*/
@CacheEvict(value = "user", key = "#id")
@Override
public void delete(Long id) {
studyMapper.deleteById(id);
log.info("删除用户【id】= {}", id);
}
}
pom.xml
<dependencies>
<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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- 引入 jackson 对象json转换 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
<!-- 对象池,使用redis时必须引入 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.21</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1.tmp</version>
</dependency>
</dependencies>
yml配置文件
server:
port: 8080
spring:
datasource:
name: study
url: jdbc:mysql://localhost:3306/database?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
druid:
initialSize: 1
minIdle: 1
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: false
maxOpenPreparedStatements: 20
#开启StatFilter
filter:
stat:
enabled: true
log-slow-sql: true
slow-sql-millis: 1000
#开启Slf4jFilter
slf4j:
enabled: true
data-source-log-enabled: false
connection-log-enabled: false
statement-log-enabled: false
result-set-log-enabled: false
#开启WallFilter
wall:
enabled: true
log-violation: true
throw-exception: false
config:
delete-where-none-check: true
#开启Web监控
web-stat-filter:
enabled: true
exclusions: /druid/*,*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico
url-pattern: /*
#开启监控页面
stat-view-servlet:
enabled: true
login-username: admin
login-password: 123456
redis:
database: 0
host: 127.0.0.1
password:
port: 6379
timeout: 1000
lettuce:
pool:
max-active: 20
max-wait: -1
max-idle: 10
min-idle: 0
@EnableCaching表明开启缓存,Spring Boot 会自动配置 Redis 缓存的 CacheManager
@SpringBootApplication
@EnableCaching
public class Redis2Application {
public static void main(String[] args) {
SpringApplication.run(Redis2Application.class, args);
}
}
查询测试
@Slf4j
public class UserServiceTest extends Redis2ApplicationTests {
@Autowired
private StudyService studyService;
/**
* 获取两次,查看日志验证缓存
*/
@Test
public void getTwice() {
// 模拟查询id为1的用户
User user1 = studyService.get(5L);
System.out.println(user1);
//log.debug("【user1】= {}", user1);
再次查询
//User user2 = studyService.get(1L);
System.out.println(user2);
//log.info("【user2】= {}"+user2.toString());
查看日志,只打印一次日志,证明缓存生效
}
}