FavoriteServiceImpl.java 5.84 KB
package com.yohoufo.user.service.impl;

import com.yohoufo.dal.user.IUserFavoriteDao;
import com.yohoufo.dal.user.model.UserFavorite;
import com.yohoufo.user.cache.CacheService;
import com.yohoufo.user.requestVO.FavoriteRequestVO;
import com.yohoufo.user.service.IFavoriteService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service("favoriteServiceImpl")
public class FavoriteServiceImpl implements IFavoriteService {

    private Logger logger = LoggerFactory.getLogger(FavoriteServiceImpl.class);

    @Autowired
    private IUserFavoriteDao userFavoriteDao;

    @Autowired
    private CacheService cacheService;


    public void addFavorite(FavoriteRequestVO vo){
        logger.info("RealNameAuthorizeServiceImpl addFavorite vo {}",vo);

        //判断redis是否存在该key,如果不存在先获取所有商品并放入缓存
        boolean isHas = cacheService.hasUserFavoriteProductKey(vo.getUid(),true);
        if(!isHas){
            List<UserFavorite> favoriteList = userFavoriteDao.selectValidFavoriteByUid(getTableIndex(vo.getUid()), vo.getUid());
            cacheService.batchSetFavoriteProduct(vo.getUid(), favoriteList);
        }

        if(!cacheService.isExistUserProductFavoriteByProductId(vo.getUid(), vo.getProductId(),false)){
            //收藏
            LocalDateTime now=LocalDateTime.now();
            long ts=now.toEpochSecond(ZoneOffset.of("+8"));
            UserFavorite userFavorite=new UserFavorite();
            userFavorite.setUid(vo.getUid());
            userFavorite.setProductId(vo.getProductId());
            userFavorite.setValidStatus(1);
            userFavorite.setCreateTime(ts);
            userFavorite.setUpdateTime(ts);
            logger.info("RealNameAuthorizeServiceImpl addFavorite userFavorite {}",userFavorite);
            userFavoriteDao.insert(getTableIndex(vo.getUid()),userFavorite);
            //放到缓存
            cacheService.addFavoriteProductKey(vo.getUid(), vo.getProductId(), ts);
        }
    }


    public void cancelFavorite(FavoriteRequestVO vo){
        LocalDateTime now=LocalDateTime.now();
        long ts=now.toEpochSecond(ZoneOffset.of("+8"));
        //删除用户的缓存
        cacheService.removeUserFavoriteProduct(vo.getUid(),vo.getProductId());
        //删除数据库,逻辑删除
        userFavoriteDao.updateFavoriteInvalid(getTableIndex(vo.getUid()),vo.getUid(), vo.getProductId(),ts);
    }


    public List<String> listFavorite(FavoriteRequestVO vo){
        List<String> favoriteProducts = new ArrayList<>();
        int uid = vo.getUid();
        int startIndex=vo.getLimit()*(vo.getPage()-1);
        int endIndex=vo.getLimit()*vo.getPage();
        // 查询缓存
        Set<String> favoriteProductIds = cacheService.queryAllProductFavoriteByUid(uid, startIndex, endIndex-1);
        if(CollectionUtils.isNotEmpty(favoriteProductIds)){
            favoriteProductIds.remove("0");
            favoriteProducts.addAll(favoriteProductIds);
            return favoriteProducts;
        }

        List<UserFavorite> favoriteList = userFavoriteDao.selectValidFavoriteByUid(getTableIndex(uid), uid);
        cacheService.batchSetFavoriteProduct(uid, favoriteList);
        int count=0;
        for (UserFavorite favorite : favoriteList) {
            if(count>=startIndex && count<endIndex){
                favoriteProducts.add(String.valueOf(favorite.getProductId()));
            }
        }
        return favoriteProducts;
    }


    /**
     * 查询某用户是否已收藏某商品 (如果存在则将失效时间延期)
     */
    public boolean isFavorite(FavoriteRequestVO vo){
        try {
            boolean existFlag = cacheService.isExistUserProductFavoriteByProductId(vo.getUid(), vo.getProductId(),false);
            if (existFlag) {
                return true;
            } else {
                if (!cacheService.hasUserFavoriteProductKey(vo.getUid(),false)) {
                    List<UserFavorite> favoriteList = userFavoriteDao.selectValidFavoriteByUid(getTableIndex(vo.getUid()), vo.getUid());
                    cacheService.batchSetFavoriteProduct(vo.getUid(), favoriteList);
                    return containsProductSku(favoriteList, vo.getProductId());
                }
                return false;
            }
        }
        catch(Exception e) {
            logger.warn("isFavorite failed userId is:{},product sku is:{}",vo.getUid(),vo.getProductId());
            return false;			//无关紧要的逻辑抛了异常也不能影响
        }
    }

    // 是否已经收藏商品
    private boolean containsProductSku(List<UserFavorite> favoriteList, Integer productId) {
        boolean curEquals = false;
        for (UserFavorite favorite : favoriteList) {		// 数据库查询出来的list肯定不为null
            curEquals = productId.equals(favorite.getProductId());
            if (curEquals) {
                return curEquals;
            }
        }
        return curEquals;
    }

    public int numFavorite(FavoriteRequestVO vo){
        int count=(int)cacheService.queryUserProductFavoriteCount(vo.getUid());
        if(count > 0){
            return count -1;
        }

        List<UserFavorite> favoriteList = userFavoriteDao.selectValidFavoriteByUid(getTableIndex(vo.getUid()), vo.getUid());
        cacheService.batchSetFavoriteProduct(vo.getUid(), favoriteList);
        count = favoriteList.size();
        return count;
    }

    private String getTableIndex(Integer uid) {
        return String.valueOf(uid % 10);
    }
}