//{[1,2],[1],[3],[1,2,3]}[1,2,3] 
//查询标签字段内容列表 将集合转换set 对内容进行去重操作
Set<String> tags = articles.stream()
        .map(Articles::getTags)
        .flatMap(s -> Arrays.stream(s.split(",")))
        .collect(Collectors.toSet());

查询字段里面有”,逗号”分隔 的内容用WHERE FIND_IN_SET 函数
SELECT * FROM content WHERE FIND_IN_SET(‘2’, tags) AND id <> 1

访问量使用redis has类型 k存id v存数量 定时获取redis map的集合 根据id修改view 入库

访问文章时 将访问量存入redis
@Override
public RecomNovice getNoviceById(Long id) {
    //获取文章内容
    RecomNovice noviceById = recomNoviceMapper.getNoviceById(id, Constans.RECOMMEND);
    if(noviceById!=null){
        //访问量放入redis
        saveRecomNoviceView(id);
    }
    return noviceById;
}

private Object saveRecomNoviceView(Long id) {
    //将id转为string
    String s = id.toString();
    //创建 key 名为NoviceViews value是id
    Object noviceViews = redisUtils.hget("NoviceViews", s);
    if(ObjectUtils.isEmpty(noviceViews)){
        //hash递增 如果不存在,就会创建一个 并把新增后的值返回
        redisUtils.hincr("NoviceViews",s,1);
    }else {
        redisUtils.hincr("NoviceViews",s,1);
    }
    return redisUtils.hget("NoviceViews",s);
}
@Scheduled(cron = "0 0/1 * * * ? ")
public void syncNoviceViews(){
    Map<Object, Object> noviceViews = redisUtils.hmget("NoviceViews");
    if(noviceViews.size()>0){
        for (Object key:noviceViews.keySet()
        ) {
            RecomNovice recomNovice = new RecomNovice();
            recomNovice.setId(Long.valueOf(key.toString()));
            recomNovice.setView(Long.valueOf(noviceViews.get(key).toString()) );
            recomNoviceMapper.updateById(recomNovice);
        }
    }


}
字符串逗号拆分成list
String str ="a,b,c";
List<String> split= Arrays.asList(str.split(","));

Redis存入数据出现乱码问题


/**
 * 设置 redisTemplate 的序列化设置
 * @param redisConnectionFactory
 * @return
 */
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    // 1.创建 redisTemplate 模版
    RedisTemplate<Object, Object> template = new RedisTemplate<>();
    // 2.关联 redisConnectionFactory
    template.setConnectionFactory(redisConnectionFactory);
    // 3.创建 序列化类
    GenericToStringSerializer genericToStringSerializer = new GenericToStringSerializer(Object.class);
    // 6.序列化类,对象映射设置
    // 7.设置 value 的转化格式和 key 的转化格式
    template.setValueSerializer(genericToStringSerializer);
    template.setKeySerializer(new StringRedisSerializer());
    template.setHashKeySerializer(new StringRedisSerializer());
    template.setHashValueSerializer(new StringRedisSerializer());
    template.afterPropertiesSet();
    return template;
}

上一篇 下一篇