redis + springboot服务器定时事件实现热点数据的存储

   

最近做的一个论坛项目发现,热门榜单文章信息和最新发布的文章信息经常需要访问,这样的话,就把它们存储在redis里吧。

先写个redisUitls,这样就可以直接存储java对象,很方便。

redisUitls.java

package com.protal.community.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 根据key读取数据
     */
    public Object get(final String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        try {
            return redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 写入数据
     */
    public boolean set(final String key, Object value) {
        if (StringUtils.isBlank(key)) {
            return false;
        }
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

 

RedisConfig配置类
package com.protal.community.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration
public class RedisConfig {

    /**
     * RedisTemplate配置
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        // 设置序列化
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        RedisSerializer<?> stringSerializer = new StringRedisSerializer();
        // key序列化
        redisTemplate.setKeySerializer(stringSerializer);
        // value序列化
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // Hash key序列化
        redisTemplate.setHashKeySerializer(stringSerializer);
        // Hash value序列化
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

再写个定时器事件类,设置每隔5分钟更新一次redis中的数据

@Component
public class TimerTask {
    @Autowired
    private ArticalInformationService articalInformationService;

    @Autowired
    private RedisUtils redisUtils;


    @Async
    @Scheduled(fixedRate = 5 * 1000 * 60)
    public void updateNewArtical() throws IOException {
        List<ArticalInformation> newArtical = articalInformationService.getNewArtical();
        redisUtils.set("newArtical",newArtical);
        for (ArticalInformation articalInformation : newArtical){
            Integer id = articalInformation.getId();
            String encoding = "UTF-8";
            File file = new File("F:\\site_data\\artical\\" + id.toString() +".txt");
            Long filelength = file.length();
            byte[] filecontent = new byte[filelength.intValue()];
            try {
                FileInputStream in = new FileInputStream(file);
                in.read(filecontent);
                String s = new String(filecontent, encoding);
                redisUtils.set("newArtical" + id.toString(),s);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                in.close();
            }
        }
    }


    @Async
    @Scheduled(fixedRate = 5 * 1000 * 60)
    public void updateHotArtical() throws IOException {
        List<ArticalVisit> hotArtical1 = articalInformationService.getHotArtical();
        List<ArticalInformation> hotArtical = new ArrayList<>();
        for(ArticalVisit articalVisit:hotArtical1){
            Integer id = articalVisit.getAid();
            ArticalInformation articalInformation = articalInformationService.selectArticalInformationById(id);
            hotArtical.add(articalInformation);
            String encoding = "UTF-8";
            File file = new File("F:\\site_data\\artical\\" + id.toString() +".txt");
            Long filelength = file.length();
            byte[] filecontent = new byte[filelength.intValue()];
            try {
                FileInputStream in = new FileInputStream(file);
                in.read(filecontent);
                String s = new String(filecontent, encoding);
                redisUtils.set("hotArtical" + id.toString(),s);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                in.close();
            }
        }
        redisUtils.set("hotArtical",hotArtical);

        //此处欠缺每次获取热榜后对表的操作,写完后边再补全
    }

}

 好的,大功告成。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值