config
@Configuration // @EnableCaching @EnableAspectJAutoProxy // 开启AOP自动代理 public class AppConfig { @Value("${spring.redis.host}") String host; @Value("${spring.redis.port}") int port; // 创建对象,spring托管 <bean ... @Bean public JedisPool jedisPool() { JedisPool jedisPool = new JedisPool("localhost", 6379); return jedisPool; } @Bean public RedisTemplate redisTemplate() { RedisTemplate redisTemplate = new RedisTemplate(); redisTemplate.setConnectionFactory(redisConnectionFactory()); return redisTemplate; } @Bean public RedisConnectionFactory redisConnectionFactory() { RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); redisStandaloneConfiguration.setHostName(host); redisStandaloneConfiguration.setPort(port); RedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration); return redisConnectionFactory; } @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory()); RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig(); CacheManager cacheManager = new RedisCacheManager(redisCacheWriter, redisCacheConfiguration); return cacheManager; } }
service
@Service public class UserService { @Autowired JdbcTemplate jdbcTemplate; // spring提供jdbc一个工具(mybastis类似) @Autowired RedisTemplate redisTemplate; /** * 根据ID查询用户信息 (redis缓存,用户信息以json字符串格式存在(序列化)) */ @Cacheable(value="user",key="#userId") // 返回值 存到redis public User findUserById(String userId) { System.out.println("查询数据库."); String sql = "select * from tb_user_base where uid=?"; User user = jdbcTemplate.queryForObject(sql, new String[]{userId}, new BeanPropertyRowMapper<>(User.class)); return user; } @CacheEvict(value="user",key="#user.uid") // 方法执行结束,清除缓存 public void updateUser(User user){ String sql = "update tb_user_base set uname=? where uid=?"; jdbcTemplate.update(sql, new String[]{user.getUname(), user.getUid()}); } }