<dependencies> <!--web项目的依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--mybatis依赖--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> <!--连接数据库的依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.49</version> <scope>runtime</scope> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!--redis与springboot集成依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.4.5</version> </dependency> </dependencies>
@Configuration public class RedisConfig { @Bean public LettuceConnectionFactory factory() { LettuceConnectionFactory factory = new LettuceConnectionFactory(); factory.afterPropertiesSet(); return factory; } @Bean public RedisTemplate redisTemplate() { RedisTemplate template = new RedisTemplate(); template.setConnectionFactory(factory()); //指定redis的键值对的序列化方式默认JDK的序列化方式 template.setKeySerializer(RedisSerializer.string()); template.setValueSerializer(RedisSerializer.json()); template.setHashKeySerializer(RedisSerializer.string()); template.setHashValueSerializer(RedisSerializer.json()); return template; } }
因为Redis将数据写入缓存中,所以Redis的读取速度比数据库的速度快得多。
本次使用Redis结合Mybatis来进行增删查改,来提高访问速度。
原理大概就是进行读操作时优先读取Redis,必须保证Redis与数据库数据同步。
首先是Redis的业务层逻辑
@Service public class RedisService { @Autowired private RedisTemplate redisTemplate; /** * redis设置键值 */ public void set(String key, Object value) { redisTemplate.opsForValue().set(key, value); } /** * 设置键值对和超时时间 */ public void set(String key, Object value, Long timeout) { redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS); } /** * 获取值 */ public Object get(String key) { return redisTemplate.opsForValue().get(key); } /** * 删除键值对 */ public boolean delete(String key) { return redisTemplate.delete(key); } }
Redis与Mybatis的业务层
@Service public class UserServiceImpl implements UserService { @Autowired(required = false) UserMapper userMapper; @Autowired RedisService redisService; @Override public void add(User user) { userMapper.add(user); String key = "user_queryById_" + user.getId(); //新增数据,将该数据写入缓存中。 redisService.set(key,user); } @Override public void deleteById(Integer id) { userMapper.deleteById(id); //删除数据,将Redis对应的数据删除 redisService.delete("user_queryById_"+id); } @Override public User queryById(Integer id) { User user = null; String key = "user_queryById_" + id; //先从Redis中读取 Object o = redisService.get(key); //如果没有就读取数据库 if (o == null) { o = userMapper.queryById(id); //读取的数据加载到Redis中 redisService.set(key, o); } user = (User) o; return user; } @Override public void update(User user) { //更新数据库 userMapper.update(user); //更新redis缓存 String key = "user_queryById_" + user.getId(); redisService.set(key,user); } }
该方法不够灵活不推荐使用。
配置Redis
注意开启缓存。否则Redis的注解不生效
@Configuration @EnableCaching//开启缓存功能 public class RedisConfig { @Bean public LettuceConnectionFactory factory() { LettuceConnectionFactory factory = new LettuceConnectionFactory(); factory.afterPropertiesSet(); return factory; } @Bean public RedisTemplate redisTemplate() { RedisTemplate template = new RedisTemplate(); template.setConnectionFactory(factory()); //指定redis的键值对的序列化方式默认JDK的序列化方式 template.setKeySerializer(RedisSerializer.string()); template.setValueSerializer(RedisSerializer.json()); template.setHashKeySerializer(RedisSerializer.string()); template.setHashValueSerializer(RedisSerializer.json()); return template; } @Bean//缓存功能默认不开启,需要开启缓存功能 public CacheManager cacheManager() { //获取redis缓存配置类,设置相关的配置内容 RedisCacheConfiguration config = RedisCacheConfiguration //创建默认的缓存配置 .defaultCacheConfig() //设置超时时间ofSeconds单位是秒 .entryTtl(Duration.ofSeconds(30)) //设置缓存名称前缀 .prefixCacheNameWith("sys_") //设置缓存键值的序列化方式,键默认是使用RedisSerializer.string()字符串序列化方式,值设置为RedisSerializer.json()的序列化方式 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json())); RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(factory()); //创建Redis缓存对象 RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, config); return cacheManager; } }
使用注解
在数据库进行写操作后将Redis对应的键删除。
@Service @Primary//默认IoC注入这个对象 @Transactional public class UserServiceImpl2 implements UserService { @Autowired(required = false) UserMapper userMapper; /** * CacheEvict * 删除redis指定的键,在执行对应的方法后 */ @Override @CacheEvict(value = "user",key = "'user_'+#id") public void deleteById(Integer id) { userMapper.deleteById(id); } /** * 先查询缓存中是否存在对应的Key,缓存名称前缀+value+key=useruser::user_id * 如果存在直接返回数据,如果不存在,再执行方法获取数据库数据,然后保存到缓存 */ @Override @Cacheable(value = "user",key = "'user_'+#id") public User queryById(Integer id) { return userMapper.queryById(id); } /** * CacheEvict * 删除redis指定的键,在执行对应的方法后 */ @Override @CacheEvict(value = "user",key = "'user_'+#user.id") public void update(User user) { userMapper.update(user); } }