pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
添加@EnableCaching
@SpringBootApplication
@EnableCaching
public class SpringBootRedisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootRedisApplication.class, args);
}
}
RedisConfig
@Configuration
public class RedisConfig {
@Bean
public RedisConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory("192.168.1.170", 6379);
}
@Bean
public RedisTemplate redisTemplate() {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(redisConnectionFactory());
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
return redisTemplate;
}
@Bean
public CacheManager cacheManager() {
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory());
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
}
}
UserDto
public class UserDto implements Serializable {
private String userId;
private String userName;
UserService
@Service
public class UserService {
@Cacheable(cacheManager = "cacheManager", value = "cache-1", key = "#userId")
public UserDto findUserById(String userId) throws Exception {
UserDto user = new UserDto(userId, "张三");
System.out.println("从数据库中读取到数据:" + user);
return user;
}
@CacheEvict(cacheManager = "cacheManager", value = "cache-1", key = "#userId")
public void deleteUserById(String userId) throws Exception {
System.out.println("用户从数据库删除成功,请检查缓存是否清除~~" + userId);
}
@CachePut(cacheManager = "cacheManager", value = "cache-1", key = "#user.userId", condition = "#result ne null")
public UserDto updateUser(UserDto user) throws Exception {
System.out.println("数据库进行了更新,检查缓存是否一致");
return user;
}
}
单元测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootRedisApplicationTests {
@Autowired
private UserService userService;
@Test
public void testQuery() throws Exception {
UserDto userDto = userService.findUserById("1");
System.out.println(userDto);
}
@Test
public void testUpdate() throws Exception {
userService.updateUser(new UserDto("1", "李四"));
testQuery();
}
@Test
public void testRemove() throws Exception {
userService.deleteUserById("1");
System.out.println("请使用 `keys *` 命令检查 key `cache-1::1`是否还存在");
}
}