springboot 整合 redis缓存
pom文件
application.properties文件
# mysql
spring.datasource.url=jdbc:mysql://localhost:3306/cache?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# mapper.xml文件所在位置,我放到了resources下面
mybatis.mapperLocations=classpath:mapper/*.xml
<!--日志显示级别,com.project是项目的前缀-->
logging.level.com.fliang=WARN
<!--在dao包执行时,输出sql,com.project.sccl.dao就是dao包的全路径-->
logging.level.com.fliang.cache.dao=DEBUG
<!--日志的输出位置-->
logging.file=logs/spring-boot-logging.log
spring.redis.host=127.0.0.1
spring.redis.port=6379
编写序列化规则json
@Configuration
public class MyRedisConfig {
@Bean
public RedisTemplate<Object,User> userRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws Exception{
RedisTemplate<Object,User> template= new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<User> userJackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer<User>(User.class);
template.setDefaultSerializer(userJackson2JsonRedisSerializer);
return template;
}
@Bean
public RedisCacheManager userRedisCacheManager(RedisTemplate<Object,User> userRedisTemplate){
RedisCacheManager userCache= new RedisCacheManager(userRedisTemplate);
userCache.setUsePrefix(true);
return userCache;
}
}
实体类
public class User implements Serializable {
private Integer userId;
private String userName;
private String password;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
测试
@Autowired
RedisTemplate<Object,User> userRedisTemplate;
@Test
public void Test02(){
User user=userService.getOne(1);
// redisTemplate.opsForValue().set("user-1",user);
userRedisTemplate.opsForValue().set("user-1",user);
}
结果