RecommendService.java 6.38 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
package com.tanpu.community.service;

import com.tanpu.common.util.JsonUtil;
import com.tanpu.community.api.beans.qo.ThemeAnalysDO;
import com.tanpu.community.api.beans.resp.PythonResponse;
import com.tanpu.community.dao.entity.community.ThemeEntity;
import com.tanpu.community.util.ConvertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RecommendService {

    @Value("${recommend.python.enable}")
    public String enablePython;


    @Value("${recommend.python.url}")
    public String pythonUrl;
    @Value("${recommend.ratio.hot}")
    public Integer hotRatio;
    @Value("${recommend.ratio.new}")
    public Integer newRatio;
    @Value("${recommend.ratio.python}")
    public Integer pythonRatio;


    @Autowired
    private RankService rankService;

    @Autowired
    private ThemeService themeService;

42 43 44
    @Autowired
    private VisitSummaryService visitSummaryService;

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
    //最新
    private List<ThemeAnalysDO> recentThemeList = new ArrayList<>();
    //推荐
    private Map<String, List<String>> recommondList = new HashMap<>();
    //
    private Map<String, Set<String>> returnedIdsMap = new HashMap<>();

    public List<String> getRecommendThemes(String lastId, Integer pageSize, String userId) {
        //最热话题,剔除当前用户的主题
        List<String> hotThemeIds = rankService.getRankThemeList().stream()
                .filter(o -> !userId.equals(o.getAuthorId()))
                .map(ThemeAnalysDO::getThemeId)
                .collect(Collectors.toList());

        //最新话题,剔除当前用户的主题
        List<String> newThemeIds = this.getRecentThemeList().stream()
                .filter(o -> !userId.equals(o.getAuthorId()))
                .map(ThemeAnalysDO::getThemeId)
                .collect(Collectors.toList());

        //推荐话题
        List<String> recThemeIds = getPythonRecommendList(userId);

        //混合
刘基明's avatar
刘基明 committed
69 70 71
        Set<String> returnedIds = (StringUtils.isEmpty(lastId)) || !returnedIdsMap.containsKey(userId)
                || returnedIdsMap.get(userId) == null ?
                new HashSet<>() : returnedIdsMap.get(userId);
72
        List<String> result = new ArrayList<>();
刘基明's avatar
刘基明 committed
73
        getResultList(hotThemeIds, 0, newThemeIds, 0, recThemeIds, 0, returnedIds, result, pageSize, userId);
74 75
        result = result.stream().limit(pageSize).collect(Collectors.toList());
        //记录已返回主题id
刘基明's avatar
刘基明 committed
76 77 78
        if (StringUtils.isEmpty(lastId)) {
            returnedIdsMap.put(userId, new HashSet<>(result));
        } else {
79 80 81
            HashSet<String> newSet = new HashSet<>();
            newSet.addAll(returnedIdsMap.get(userId));
            newSet.addAll(result);
刘基明's avatar
刘基明 committed
82
            returnedIdsMap.put(userId, newSet);
83 84
        }
        return result;
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    }

    public List<ThemeAnalysDO> getRecentThemeList() {
        if (recentThemeList.size() == 0) {
            refreshNewestThemes();
        }
        return recentThemeList;
    }

    //从数据库查询最新主题
    public void refreshNewestThemes() {
        List<ThemeEntity> themeEntities = themeService.queryLatestThemes(100);
        this.recentThemeList = ConvertUtil.themeEntityToAnalysDOs(themeEntities);
    }

    //查询python计算推荐列表
    public List<String> getPythonRecommendList(String userId) {
        if (recommondList.containsKey(userId)) {
            return recommondList.get(userId);
        } else {
            return refreshPythonRecommendList(userId);
        }
    }


    //HTTP查询python推荐主题
    public List<String> refreshPythonRecommendList(String userId) {
        if (!"true".equals(enablePython)) {
            return Collections.emptyList();
        }
        RestTemplate restTemplate = new RestTemplate();
        HashMap<String, String> param = new HashMap<>();
        param.put("user_id", userId);
        try {
            String response = restTemplate.getForObject(pythonUrl, String.class, param);
            PythonResponse pythonResponse = JsonUtil.toBean(response, PythonResponse.class);
            recommondList.put(userId, pythonResponse.getAttributes());
            return pythonResponse.getAttributes();
        } catch (Exception e) {
            log.error("调用python失败");
            return Collections.emptyList();
        }


    }

    //逐个插入
132
    private void getResultList(List<String> hotThemeIds, Integer hotTag, List<String> newThemeIds, Integer newTag, List<String> recThemeIds, Integer recTag, Set<String> returnedIds, List<String> result, Integer pageSize, String userId) {
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
        if (hotThemeIds.size() <= hotTag && newThemeIds.size() <= newTag && recThemeIds.size() <= recTag) {
            //所有列表已循环结束,返回
            return;
        }

        while (result.size() < pageSize * 1.5) {
            int hotTimes = hotRatio;
            int newTimes = newRatio;
            int recTimes = pythonRatio;
            String id;
            while (hotTimes > 0 && hotThemeIds.size() > hotTag) {
                id = hotThemeIds.get(hotTag);
                if (!returnedIds.contains(id)) {
                    result.add(id);
                    returnedIds.add(id);
                }
                hotTag++;
                hotTimes--;
            }
            while (newTimes > 0 && newThemeIds.size() > newTag) {
                id = newThemeIds.get(newTag);
                if (!returnedIds.contains(id)) {
                    result.add(id);
                    returnedIds.add(id);
                }
                newTag++;
                newTimes--;
            }
            while (recTimes > 0 && recThemeIds.size() > recTag) {
                id = recThemeIds.get(recTag);
                if (!returnedIds.contains(id)) {
                    result.add(id);
                    returnedIds.add(id);
                }
                recTag++;
                recTimes--;
            }

        }
172
        //去重已看过(查看正文)
刘基明's avatar
刘基明 committed
173
        result = visitSummaryService.filterUserNotVisited(userId, result);
174 175

        if (result.size() < pageSize) {
176
            getResultList(hotThemeIds, hotTag, newThemeIds, newTag, recThemeIds, recTag, returnedIds, result, pageSize, userId);
177 178 179 180 181
        }
    }


}