SpringBoot云 & 网站Java

SpringBoot+Redis实现缓存

2020-03-19  本文已影响0人  HeloWxl

1、引入依赖 pom.xml

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
 </dependency>

2、application.yml

   redis:
       database: 0
       host: localhost
       port: 6379
       password:  #如果没设置密码就没有密码,设置了才会有
       timeout: 6000ms
       jedis:
         pool:
           max-active: 200 #连接池最大连接数(适用负值表示没有限制)
           max-wait: -1  #连接池最大阻塞等待时间(适用负值表示没有限制)
           max-idle: 10 #连接池中的最大空闲连接
           min-idle: 0 #连接池中的最小空闲连接

3、RedisConfig

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        // 设置缓存有效期一小时
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1));
        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration).build();
    }
  
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 对hash类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }

    /**
     * 对redis字符串类型数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }

    /**
     * 对链表类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }

    /**
     * 对无序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }

    /**
     * 对有序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();
    }
}

4、ServiceImpl

@Service("artileService")
@Slf4j
public class ArtileServiceImpl implements ArtileService {
    @Resource
    private ArtileDao artileDao;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
    * @Description: 分页查询 :注意这里需要进行一下对分页数据的处理 (offset-1)*limit, limit
    * @params: [offset, limit]
    * @return: java.util.List<com.ustcinfo.cache.entity.Artile>
    * @Author: wangxianlin
    * @Date: 2020/3/17 10:57 AM
    */
    @Override
    public Artile queryById(int id) {
        ValueOperations<String, Artile> operations = redisTemplate.opsForValue();
        //判断redis中是否有键为key的缓存
        boolean hasKey = redisTemplate.hasKey("artile_"+id);
        if (hasKey) {
            Artile artile = operations.get("artile_"+id);
            log.info("从缓存中获得数据:"+artile.getTitle());
            log.info("------------------------------------");
            return artile;
        } else {
            Artile artile = artileDao.queryById(id);
            log.info("查询数据库获得数据:"+id);
            log.info("------------------------------------");
            // 写入缓存
            operations.set(String.valueOf("artile_"+id), artile, 5, TimeUnit.HOURS);
            return artile;
        }
    }

    /**
    * @Description: 新增数据
    * @params: [artile]
    * @return: int
    * @Author: wangxianlin
    * @Date: 2020/3/17 10:57 AM
    */
    @Override
    public int insert(Artile artile) {
        return this.artileDao.insert(artile);
    }

    /**
    * @Description: 修改数据  :先更新数据表,成功之后,删除原来的缓存,再更新缓存
    * @params: [artile]
    * @return: com.ustcinfo.cache.entity.Artile
    * @Author: wangxianlin
    * @Date: 2020/3/17 10:57 AM
    */
    @Override
    public int update(Artile artile) {
        ValueOperations<String, Artile> operations = redisTemplate.opsForValue();
        int result = artileDao.update(artile);
        if (result != 0) {
            String key = "artile_" + artile.getId();
            boolean haskey = redisTemplate.hasKey(key);
            if (haskey) {
                redisTemplate.delete(key);
                log.info("删除缓存中的key-----------> " + key);
            }
            // 再将更新后的数据加入缓存
            Artile artile1 = artileDao.queryById(artile.getId());
            if (artile1 != null) {
                operations.set(key, artile1, 3, TimeUnit.HOURS);
            }
        }
        return  result;
    }

    /**
    * @Description: 根据主键删除
    * @params: [id]
    * @return: boolean
    * @Author: wangxianlin
    * @Date: 2020/3/17 10:58 AM
    */
    @Override
    public boolean deleteById(Integer id) {
        int result = artileDao.deleteById(id);
        String key = "artile_" + id;
        if (result != 0) {
            boolean hasKey = redisTemplate.hasKey(key);
            if (hasKey) {
                redisTemplate.delete(key);
                log.info("删除了缓存中的key:" + key);
            }
        }
        return result>0;
    }
}

5、启动Redis

image.png

6、测试

6.1 根据ID查询

6.2 新增

6.3 修改

image.png

6.4 删除

上一篇下一篇

猜你喜欢

热点阅读