浏览代码

Merge branch 'feature_refactor' of algorithm/recommend-server into master

dingyunpeng 3 月之前
父节点
当前提交
ec9ceadeb0

+ 0 - 195
recommend-server-service/src/main/java/com/tzld/piaoquan/recommend/server/dataloader/FeatureConstructor.java

@@ -1,195 +0,0 @@
-package com.tzld.piaoquan.recommend.server.dataloader;
-
-
-import com.aliyun.odps.Instance;
-import com.aliyun.odps.Odps;
-import com.aliyun.odps.OdpsException;
-import com.aliyun.odps.account.Account;
-import com.aliyun.odps.account.AliyunAccount;
-import com.aliyun.odps.data.Record;
-import com.aliyun.odps.task.SQLTask;
-import com.aliyun.odps.tunnel.InstanceTunnel;
-import com.aliyun.odps.tunnel.io.TunnelRecordReader;
-import com.tzld.piaoquan.recommend.feature.domain.video.base.ItemFeature;
-import com.tzld.piaoquan.recommend.feature.domain.video.base.RequestContext;
-import com.tzld.piaoquan.recommend.feature.domain.video.base.UserActionFeature;
-import com.tzld.piaoquan.recommend.feature.domain.video.base.UserFeature;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class FeatureConstructor {
-
-    private static final String BUCKET_NAME = "ali-recommend";
-    private static final Map<String, String> ODPS_CONFIG = new HashMap<String, String>();
-
-    static {
-        ODPS_CONFIG.put("ENDPOINT", "http://service.cn.maxcompute.aliyun.com/api");
-        ODPS_CONFIG.put("ACCESSID", "LTAIWYUujJAm7CbH");
-        ODPS_CONFIG.put("ACCESSKEY", "RfSjdiWwED1sGFlsjXv0DlfTnZTG1P");
-    }
-
-    ;
-
-    private static final Account account = new AliyunAccount(ODPS_CONFIG.get("ACCESSID"), ODPS_CONFIG.get("ACCESSKEY"));
-
-
-    public static TunnelRecordReader loadDataFromOSSSession(String sql) {
-        Odps odps = new Odps(account);
-        odps.setEndpoint(ODPS_CONFIG.get("ENDPOINT"));
-        odps.setDefaultProject("loghubods");
-        TunnelRecordReader reader = null;
-        try {
-            Instance instance = SQLTask.run(odps, sql);
-            instance.waitForSuccess();
-            InstanceTunnel tunnel = new InstanceTunnel(odps);
-            InstanceTunnel.DownloadSession session = tunnel.createDownloadSession(odps.getDefaultProject(), instance.getId());
-            long count = session.getRecordCount();
-            reader = session.openRecordReader(0, count);
-        } catch (OdpsException e) {
-            e.printStackTrace();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-        return reader;
-    }
-
-
-    public static RequestContext constructRequestContext(Record record) {
-        RequestContext requestContext = new RequestContext();
-        requestContext.setApptype(record.getString("apptype"));
-        requestContext.setMachineinfo_brand(record.getString("machineinfo_brand"));
-        requestContext.setMachineinfo_model(record.getString("machineinfo_model"));
-        requestContext.setMachineinfo_platform(record.getString("machineinfo_platform"));
-        requestContext.setMachineinfo_sdkversion(record.getString("machineinfo_sdkversion"));
-        requestContext.setMachineinfo_system(record.getString("machineinfo_system"));
-        requestContext.setMachineinfo_wechatversion(record.getString("machineinfo_wechatversion"));
-        requestContext.setDay(record.getString("ctx_day"));
-        requestContext.setWeek(record.getString("ctx_week"));
-        requestContext.setHour(record.getString("ctx_hour"));
-        requestContext.setRegion(record.getString("ctx_region"));
-        requestContext.setCity(record.getString("ctx_city"));
-        return requestContext;
-    }
-
-
-    public static UserFeature constructUserFeature(Record record) {
-        UserFeature userFeature = new UserFeature();
-        userFeature.setUid(record.get("uid").toString());
-        userFeature.setUser_cycle_bucket_7days(record.getString("u_cycle_bucket_7days"));
-        userFeature.setUser_cycle_bucket_30days(record.getString("u_cycle_bucket_30days"));
-        userFeature.setUser_share_bucket_30days(record.getString("u_share_bucket_30days"));
-
-
-        // 1day features
-        UserActionFeature user1dayActionFeature = new UserActionFeature();
-        user1dayActionFeature.setExp_cnt(record.getString("u_1day_exp_cnt"));
-        user1dayActionFeature.setClick_cnt(record.getString("u_1day_click_cnt"));
-        user1dayActionFeature.setShare_cnt(record.getString("u_1day_share_cnt"));
-        user1dayActionFeature.setReturn_cnt(record.getString("u_1day_return_cnt"));
-        user1dayActionFeature.setCtr(record.getString("u_ctr_1day"));
-        user1dayActionFeature.setStr(record.getString("u_str_1day"));
-        user1dayActionFeature.setRov(record.getString("u_rov_1day"));
-        user1dayActionFeature.setRos(record.getString("u_ros_1day"));
-        userFeature.setDay1_cnt_features(user1dayActionFeature);
-
-        // 3day features
-        UserActionFeature user3dayActionFeature = new UserActionFeature();
-        user3dayActionFeature.setExp_cnt(record.getString("u_3day_exp_cnt"));
-        user3dayActionFeature.setClick_cnt(record.getString("u_3day_click_cnt"));
-        user3dayActionFeature.setShare_cnt(record.getString("u_3day_share_cnt"));
-        user3dayActionFeature.setReturn_cnt(record.getString("u_3day_return_cnt"));
-        user3dayActionFeature.setCtr(record.getString("u_ctr_3day"));
-        user3dayActionFeature.setStr(record.getString("u_str_3day"));
-        user3dayActionFeature.setRov(record.getString("u_rov_3day"));
-        user3dayActionFeature.setRos(record.getString("u_ros_3day"));
-        userFeature.setDay3_cnt_features(user3dayActionFeature);
-
-        // 7day features
-        UserActionFeature user7dayActionFeature = new UserActionFeature();
-        user7dayActionFeature.setExp_cnt(record.getString("u_7day_exp_cnt"));
-        user7dayActionFeature.setClick_cnt(record.getString("u_7day_click_cnt"));
-        user7dayActionFeature.setShare_cnt(record.getString("u_7day_share_cnt"));
-        user7dayActionFeature.setReturn_cnt(record.getString("u_7day_return_cnt"));
-        user7dayActionFeature.setCtr(record.getString("u_ctr_7day"));
-        user7dayActionFeature.setStr(record.getString("u_str_7day"));
-        user7dayActionFeature.setRov(record.getString("u_rov_7day"));
-        user7dayActionFeature.setRos(record.getString("u_ros_7day"));
-        userFeature.setDay7_cnt_features(user7dayActionFeature);
-
-        // 3month features
-        UserActionFeature user3monthActionFeature = new UserActionFeature();
-        user3monthActionFeature.setExp_cnt(record.getString("u_3month_exp_cnt"));
-        user3monthActionFeature.setClick_cnt(record.getString("u_3month_click_cnt"));
-        user3monthActionFeature.setShare_cnt(record.getString("u_3month_share_cnt"));
-        user3monthActionFeature.setReturn_cnt(record.getString("u_3month_return_cnt"));
-        user3monthActionFeature.setCtr(record.getString("u_ctr_3month"));
-        user3monthActionFeature.setStr(record.getString("u_str_3month"));
-        user3monthActionFeature.setRov(record.getString("u_rov_3month"));
-        user3monthActionFeature.setRos(record.getString("u_ros_3month"));
-        userFeature.setMonth3_cnt_features(user3monthActionFeature);
-
-        return userFeature;
-    }
-
-
-    public static ItemFeature constructItemFeature(Record record) {
-        ItemFeature itemFeature = new ItemFeature();
-        itemFeature.setVideoId(record.get("videoid").toString());
-        itemFeature.setUpId(record.get("uid").toString());
-        //itemFeature.setTitleLength(record.get("play_count").toString());
-        itemFeature.setPlayLength(record.get("total_time").toString());
-        itemFeature.setTotalTime(record.get("total_time").toString());
-        itemFeature.setDaysSinceUpload(record.get("existence_days").toString());
-
-        UserActionFeature user1dayActionFeature = new UserActionFeature();
-        user1dayActionFeature.setExp_cnt(record.getString("i_1day_exp_cnt"));
-        user1dayActionFeature.setClick_cnt(record.getString("i_1day_click_cnt"));
-        user1dayActionFeature.setShare_cnt(record.getString("i_1day_share_cnt"));
-        user1dayActionFeature.setReturn_cnt(record.getString("i_1day_return_cnt"));
-        user1dayActionFeature.setCtr(record.getString("i_ctr_1day"));
-        user1dayActionFeature.setStr(record.getString("i_str_1day"));
-        user1dayActionFeature.setRov(record.getString("i_rov_1day"));
-        user1dayActionFeature.setRos(record.getString("i_ros_1day"));
-        itemFeature.setDay1_cnt_features(user1dayActionFeature);
-
-        UserActionFeature user3dayActionFeature = new UserActionFeature();
-        user3dayActionFeature.setExp_cnt(record.getString("i_3day_exp_cnt"));
-        user3dayActionFeature.setClick_cnt(record.getString("i_3day_click_cnt"));
-        user3dayActionFeature.setShare_cnt(record.getString("i_3day_share_cnt"));
-        user3dayActionFeature.setReturn_cnt(record.getString("i_3day_return_cnt"));
-        user3dayActionFeature.setCtr(record.getString("i_ctr_3day"));
-        user3dayActionFeature.setStr(record.getString("i_str_3day"));
-        user3dayActionFeature.setRov(record.getString("i_rov_3day"));
-        user3dayActionFeature.setRos(record.getString("i_ros_3day"));
-        itemFeature.setDay3_cnt_features(user1dayActionFeature);
-
-        UserActionFeature user7dayActionFeature = new UserActionFeature();
-        user7dayActionFeature.setExp_cnt(record.getString("i_7day_exp_cnt"));
-        user7dayActionFeature.setClick_cnt(record.getString("i_7day_click_cnt"));
-        user7dayActionFeature.setShare_cnt(record.getString("i_7day_share_cnt"));
-        user7dayActionFeature.setReturn_cnt(record.getString("i_7day_return_cnt"));
-        user7dayActionFeature.setCtr(record.getString("i_ctr_7day"));
-        user7dayActionFeature.setStr(record.getString("i_str_7day"));
-        user7dayActionFeature.setRov(record.getString("i_rov_7day"));
-        user7dayActionFeature.setRos(record.getString("i_ros_7day"));
-        itemFeature.setDay7_cnt_features(user1dayActionFeature);
-
-        UserActionFeature user3monthActionFeature = new UserActionFeature();
-        user3monthActionFeature.setExp_cnt(record.getString("i_3month_exp_cnt"));
-        user3monthActionFeature.setClick_cnt(record.getString("i_3month_click_cnt"));
-        user3monthActionFeature.setShare_cnt(record.getString("i_3month_share_cnt"));
-        user3monthActionFeature.setReturn_cnt(record.getString("i_3month_return_cnt"));
-        user3monthActionFeature.setCtr(record.getString("i_ctr_3month"));
-        user3monthActionFeature.setStr(record.getString("i_str_3month"));
-        user3monthActionFeature.setRov(record.getString("i_rov_3month"));
-        user3monthActionFeature.setRos(record.getString("i_ros_3month"));
-        itemFeature.setMonth3_cnt_features(user3monthActionFeature);
-        return itemFeature;
-    }
-
-
-}

+ 0 - 76
recommend-server-service/src/main/java/com/tzld/piaoquan/recommend/server/dataloader/ItemFeatureToRedisLoader.java

@@ -1,76 +0,0 @@
-package com.tzld.piaoquan.recommend.server.dataloader;
-
-import com.aliyun.odps.data.Record;
-import com.aliyun.odps.tunnel.io.TunnelRecordReader;
-import com.tzld.piaoquan.recommend.feature.domain.video.base.ItemFeature;
-import com.tzld.piaoquan.recommend.server.common.ThreadPoolFactory;
-import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
-import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
-import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.data.redis.serializer.StringRedisSerializer;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.ExecutorService;
-
-
-public class ItemFeatureToRedisLoader {
-
-    private final String videoKeyFormat = "video:%s";
-    private ExecutorService pool = ThreadPoolFactory.defaultPool();
-
-    public static RedisTemplate<String, String> buildRedisTemplate() {
-        RedisStandaloneConfiguration rsc = new RedisStandaloneConfiguration();
-        rsc.setPort(6379);
-        rsc.setPassword("Wqsd@2019");
-        rsc.setHostName("r-bp1ps6my7lzg8rdhwx682.redis.rds.aliyuncs.com");
-        RedisTemplate<String, String> template = new RedisTemplate<>();
-        JedisConnectionFactory fac = new JedisConnectionFactory(rsc);
-        fac.afterPropertiesSet();
-        template.setDefaultSerializer(new StringRedisSerializer());
-        template.setConnectionFactory(fac);
-        template.afterPropertiesSet();
-        return template;
-    }
-
-
-    public void loadFeatureToRedis(String table, String dt) {
-        RedisTemplate<String, String> redisTemplate = buildRedisTemplate();
-        String sql = String.format("select * from %s where dt ='%s';", table, dt);
-        TunnelRecordReader reader = FeatureConstructor.loadDataFromOSSSession(sql);
-        Record record;
-        Map<String, String> itemFeaRedisFormat = new HashMap<String, String>();
-        int count = 0;
-        try {
-            while ((record = reader.read()) != null) {
-                ItemFeature itemFeature = FeatureConstructor.constructItemFeature(record);
-                String key = String.format(videoKeyFormat, itemFeature.getKey());
-                String value = itemFeature.getValue();
-                itemFeaRedisFormat.put(key, value);
-                if (count < 200) {
-                    count++;
-                } else if (count == 200) {
-                    redisTemplate.opsForValue().multiSet(itemFeaRedisFormat);
-                    System.out.println("------succes add 200-----");
-                    itemFeaRedisFormat = new HashMap<String, String>();
-                    count = 0;
-                    break;
-                }
-            }
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
-
-
-    public static void main(String[] args) {
-        if (args.length < 2) {
-            System.out.println("--------args 缺失---------");
-            return;
-        }
-        ItemFeatureToRedisLoader itemFeatureToRedisLoader = new ItemFeatureToRedisLoader();
-        itemFeatureToRedisLoader.loadFeatureToRedis(args[0], args[1]);
-    }
-
-}

+ 0 - 93
recommend-server-service/src/main/java/com/tzld/piaoquan/recommend/server/dataloader/OfflineAdOutSamplesLoader.java

@@ -1,93 +0,0 @@
-package com.tzld.piaoquan.recommend.server.dataloader;
-
-import com.aliyun.odps.tunnel.io.TunnelRecordReader;
-import com.google.common.collect.ListMultimap;
-import com.tzld.piaoquan.recommend.feature.domain.video.base.*;
-import com.tzld.piaoquan.recommend.feature.domain.video.feature.VlogShareLRFeatureExtractor;
-import com.aliyun.odps.data.Record;
-import com.tzld.piaoquan.recommend.feature.model.sample.BaseFeature;
-import com.tzld.piaoquan.recommend.feature.model.sample.FeatureGroup;
-
-import java.io.IOException;
-import java.util.*;
-
-
-public class OfflineAdOutSamplesLoader {
-
-    private static final String BUCKET_NAME = "ali-recommend";
-    private static  final Map<String, String> ODPS_CONFIG =  new HashMap<String, String>();
-    static {
-        ODPS_CONFIG.put("ENDPOINT", "http://service.cn.maxcompute.aliyun.com/api");
-        ODPS_CONFIG.put("ACCESSID", "LTAIWYUujJAm7CbH");
-        ODPS_CONFIG.put("ACCESSKEY", "RfSjdiWwED1sGFlsjXv0DlfTnZTG1P");
-    };
-
-
-    // 单条日志处理逻辑
-    public static String singleParse(Record record) {
-        // 数据解析
-        String label = record.getString("ui_is_out");
-        if(label == null){
-            label = "0";
-        }
-
-        // 从sql的 record中 初始化对象内容
-        RequestContext requestContext = FeatureConstructor.constructRequestContext(record);
-        UserFeature userFeature = FeatureConstructor.constructUserFeature(record);
-        ItemFeature itemFeature =  FeatureConstructor.constructItemFeature(record);
-
-        // 转化成bytes
-        RequestContextBytesFeature requestContextBytesFeature = new RequestContextBytesFeature(requestContext);
-        UserBytesFeature userBytesFeature = new UserBytesFeature(userFeature);
-        VideoBytesFeature videoBytesFeature = new VideoBytesFeature(itemFeature);
-
-        // 特征抽取
-        VlogShareLRFeatureExtractor bytesFeatureExtractor;
-        bytesFeatureExtractor = new VlogShareLRFeatureExtractor();
-
-        bytesFeatureExtractor.getUserFeatures(userBytesFeature);
-        bytesFeatureExtractor.getItemFeature(videoBytesFeature);
-        bytesFeatureExtractor.getContextFeatures(requestContextBytesFeature);
-
-        ListMultimap<FeatureGroup, BaseFeature> featureMap = bytesFeatureExtractor.getFeatures();
-        return parseSamplesToString(label, featureMap);
-    }
-
-    // 构建样本的字符串
-    public static String parseSamplesToString(String label, ListMultimap<FeatureGroup, BaseFeature> featureMap) {
-        ArrayList<String> featureList = new ArrayList<String>();
-        for (Map.Entry<FeatureGroup, BaseFeature> entry : featureMap.entries()) {
-            FeatureGroup groupedFeature = entry.getKey();
-            BaseFeature baseFeature = entry.getValue();
-            Long featureIdentifier = baseFeature.getIdentifier();
-            featureList.add(String.valueOf(featureIdentifier) + ":1");
-        }
-        return label + "\t" + String.join("\t", featureList);
-    }
-
-
-    //  主处理逻辑
-    public static void mutiplyParser(String table, String startDay, String endDay) {
-        String sql = String.format("select * from %s where ad_ornot = '0' and apptype != '13' and dt >='%s' and dt <='%s';", table, startDay, endDay);
-        TunnelRecordReader reader = FeatureConstructor.loadDataFromOSSSession(sql);
-        Record record;
-        try {
-            while ((record = reader.read()) != null) {
-                String samples = singleParse(record);
-                System.out.println(samples);
-            }
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
-
-
-    public static void main(String[] args) {
-        if(args.length < 2){
-            System.out.println("--------args 缺失---------");
-            return;
-        }
-        OfflineAdOutSamplesLoader.mutiplyParser(args[0], args[1], args[2]);
-    }
-
-}

+ 0 - 79
recommend-server-service/src/main/java/com/tzld/piaoquan/recommend/server/dataloader/UserFeatureToRedisLoader.java

@@ -1,79 +0,0 @@
-package com.tzld.piaoquan.recommend.server.dataloader;
-
-import com.aliyun.odps.data.Record;
-import com.aliyun.odps.tunnel.io.TunnelRecordReader;
-import com.tzld.piaoquan.recommend.feature.domain.video.base.UserFeature;
-import com.tzld.piaoquan.recommend.server.common.ThreadPoolFactory;
-import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
-import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
-import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.data.redis.serializer.StringRedisSerializer;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-import java.util.concurrent.ExecutorService;
-
-
-public class UserFeatureToRedisLoader {
-
-    private final String userKeyFormat = "user:%s";
-    private ExecutorService pool = ThreadPoolFactory.defaultPool();
-
-    public static RedisTemplate<String, String> buildRedisTemplate() {
-        RedisStandaloneConfiguration rsc = new RedisStandaloneConfiguration();
-        rsc.setPort(6379);
-        rsc.setPassword("Wqsd@2019");
-        rsc.setHostName("r-bp1ps6my7lzg8rdhwx682.redis.rds.aliyuncs.com");
-        RedisTemplate<String, String> template = new RedisTemplate<>();
-        JedisConnectionFactory fac = new JedisConnectionFactory(rsc);
-        fac.afterPropertiesSet();
-        template.setDefaultSerializer(new StringRedisSerializer());
-        template.setConnectionFactory(fac);
-        template.afterPropertiesSet();
-        return template;
-    }
-
-
-
-    public void loadFeatureToRedis(String userTable, String dt) {
-        RedisTemplate<String, String> redisTemplate = buildRedisTemplate();
-        String sql = String.format("select * from %s where dt ='%s';", userTable, dt);
-        TunnelRecordReader reader = FeatureConstructor.loadDataFromOSSSession(sql);
-        Record record;
-        Map<String, String> userFeaRedisFormat = new HashMap<String, String>();
-        int count = 0;
-        try {
-            while ((record = reader.read()) != null) {
-                UserFeature userFeature = FeatureConstructor.constructUserFeature(record);
-                String key = String.format(userKeyFormat, userFeature.getKey());
-                String value = userFeature.getValue();
-                userFeaRedisFormat.put(key, value);
-                if(count < 200) {
-                    count++;
-                } else if (count == 200) {
-                    redisTemplate.opsForValue().multiSet(userFeaRedisFormat);
-                    System.out.println("------succes add 2000-----");
-                    userFeaRedisFormat = new HashMap<String, String>();
-                    count = 0;
-                    break;
-                }
-            }
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
-
-
-
-    public static void main(String[] args) {
-        if(args.length < 2){
-            System.out.println("--------args 缺失---------");
-            return;
-        }
-        UserFeatureToRedisLoader userFeatureToRedisLoader = new UserFeatureToRedisLoader();
-        userFeatureToRedisLoader.loadFeatureToRedis(args[0], args[1]);
-    }
-
-}

+ 0 - 1
recommend-server-service/src/main/java/com/tzld/piaoquan/recommend/server/service/filter/AbstractFilterService.java

@@ -64,7 +64,6 @@ public abstract class AbstractFilterService {
 
     private List<FilterStrategy> getStrategies(FilterParam param) {
         List<FilterStrategy> strategies = new ArrayList<>();
-        strategies.add(ServiceBeanFactory.getBean(SecurityStrategy.class));
         strategies.add(ServiceBeanFactory.getBean(PreViewedStrategy.class));
         strategies.add(ServiceBeanFactory.getBean(ViewedStrategy.class));
         strategies.add(ServiceBeanFactory.getBean(RecommendStatusStrategy.class));

+ 0 - 5
recommend-server-service/src/main/java/com/tzld/piaoquan/recommend/server/service/filter/FilterService.java

@@ -1,5 +0,0 @@
-package com.tzld.piaoquan.recommend.server.service.filter;
-
-public interface FilterService {
-    FilterResult filter(FilterParam param);
-}

+ 0 - 110
recommend-server-service/src/main/java/com/tzld/piaoquan/recommend/server/service/filter/VideoCityFilterService.java

@@ -1,110 +0,0 @@
-package com.tzld.piaoquan.recommend.server.service.filter;
-
-import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue;
-import com.google.common.base.Stopwatch;
-import com.tzld.piaoquan.recommend.server.repository.WxVideoTagRel;
-import com.tzld.piaoquan.recommend.server.repository.WxVideoTagRelRepository;
-import com.tzld.piaoquan.recommend.server.util.CommonCollectionUtils;
-import org.apache.commons.collections4.CollectionUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.scheduling.annotation.Scheduled;
-import org.springframework.stereotype.Service;
-
-import javax.annotation.PostConstruct;
-import javax.annotation.Resource;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
-
-/**
- * @author sunxy
- */
-@Service
-public class VideoCityFilterService {
-
-//    private final Logger logger = Logger.getLogger(VideoCityFilterService.class.getName());
-
-    private final Logger logger = LoggerFactory.getLogger(VideoCityFilterService.class);
-
-//    @Value("${video.filter.city.tagid.json:}")
-//    private String videoFilterTagIdJson;
-
-    @ApolloJsonValue("${video.filter.city.tagid.json:{}}")
-    private Map<String, List<Long>> videoFilterCityTagIdMap;
-    @Value("#{'${block.hotscenetype.list:}'.split(',')}")
-    private Set<Long> excludeScenes;
-    @Value("${securityAbExpCode:625}")
-    private String securityAbExpCode;
-    @Resource
-    private WxVideoTagRelRepository wxVideoTagRelRepository;
-    private Map<String, Set<Long>> videoTagCache = new ConcurrentHashMap<>();
-
-    @PostConstruct
-    public void init() {
-        initCacheByValue();
-    }
-
-    @Scheduled(cron = "0 0 0/2 * * ? ")
-    public void cornInit() {
-        initCacheByValue();
-    }
-
-    private void initCacheByValue() {
-        Stopwatch stopwatch = Stopwatch.createStarted();
-        if (Objects.isNull(videoFilterCityTagIdMap) || videoFilterCityTagIdMap.isEmpty()) {
-            videoTagCache = new ConcurrentHashMap<>();
-            return;
-        }
-        Map<String, Set<Long>> tmp = new ConcurrentHashMap<>();
-        for (Map.Entry<String, List<Long>> entry : videoFilterCityTagIdMap.entrySet()) {
-            if (Objects.isNull(entry)) {
-                continue;
-            }
-            String cityCode = entry.getKey();
-            List<Long> tagList = entry.getValue();
-            if (Objects.isNull(cityCode) || Objects.isNull(tagList) || tagList.isEmpty()) {
-                continue;
-            }
-            Set<Long> videosByTag = wxVideoTagRelRepository.findAllByTagIdIn(tagList).stream()
-                    .map(WxVideoTagRel::getVideoId).collect(Collectors.toSet());
-            tmp.put(cityCode, videosByTag);
-        }
-        videoTagCache = tmp;
-        logger.info("initCacheByValue videoTagCache.size = {} execute time = {}", videoTagCache.size(), stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
-
-    }
-
-    public List<Long> filterVideosByCity(List<Long> videoIds, Set<String> abExpCodes,
-                                         Long hotSceneType, String cityCode) {
-        if (CollectionUtils.isEmpty(videoIds) || StringUtils.isBlank(cityCode) || hotSceneType == null) {
-            return videoIds;
-        }
-        if (CollectionUtils.isNotEmpty(excludeScenes) && excludeScenes.contains(hotSceneType)) {
-            return videoIds;
-        }
-        if (!CommonCollectionUtils.contains(abExpCodes, securityAbExpCode)) {
-            return videoIds;
-        }
-        List<Long> tagIdList = videoFilterCityTagIdMap.get(cityCode);
-        if (tagIdList == null || tagIdList.isEmpty()) {
-            return videoIds;
-        }
-
-        Set<Long> riskCityVideoIdSet = videoTagCache.get(cityCode);
-        if (riskCityVideoIdSet == null || riskCityVideoIdSet.isEmpty()) {
-            return videoIds;
-        }
-
-        videoIds.removeIf(riskCityVideoIdSet::contains);
-
-        return videoIds;
-    }
-
-}

+ 0 - 408
recommend-server-service/src/main/java/com/tzld/piaoquan/recommend/server/service/filter/strategy/BlacklistContainer.java

@@ -1,408 +0,0 @@
-package com.tzld.piaoquan.recommend.server.service.filter.strategy;
-
-import com.aliyun.openservices.aliyun.log.producer.LogProducer;
-import com.aliyun.openservices.aliyun.log.producer.Producer;
-import com.aliyun.openservices.aliyun.log.producer.ProducerConfig;
-import com.aliyun.openservices.aliyun.log.producer.ProjectConfig;
-import com.aliyun.openservices.log.common.LogItem;
-import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue;
-import com.google.common.cache.CacheBuilder;
-import com.google.common.cache.CacheLoader;
-import com.google.common.cache.LoadingCache;
-import com.tzld.piaoquan.recommend.server.common.ThreadPoolFactory;
-import com.tzld.piaoquan.recommend.server.repository.WxVideoTagRel;
-import com.tzld.piaoquan.recommend.server.repository.WxVideoTagRelRepository;
-import lombok.Data;
-import org.apache.commons.collections4.CollectionUtils;
-import org.apache.commons.collections4.MapUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.scheduling.annotation.Scheduled;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.Nonnull;
-import javax.annotation.PostConstruct;
-import javax.annotation.Resource;
-import java.util.*;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
-
-/**
- * 黑名单列表相关的容器。主要实现以下几个功能
- * <ul>
- *     <ol>1. 判断用户属于哪个类型的黑名单</ol>
- *     <ol>2. 根据用户类型判断视频对于该用户是否有风险</ol>
- *     <ol>3. 根据用户类型过滤掉视频列表中对该用户有风险的视频</ol>
- * </ul>
- */
-@Component
-public class BlacklistContainer {
-
-
-    private static final Logger LOG = LoggerFactory.getLogger(BlacklistContainer.class);
-
-    public static final String CONNECTOR_STR = ":";
-
-    private static final int USER_REDIS_KEY_PARTITION_COUNT = 10;
-
-    /**
-     * 用户访问黑名单 Redis Key
-     */
-    private static final String USER_VISIO_BLACKLIST_HASH_KEY = "visio:blacklist:user:";
-
-    /**
-     * IP访问黑名单 Redis Key
-     */
-    private static final String IP_VISIO_BLACKLIST_HASH_KEY = "visio:blacklist:ip";
-
-    @Autowired
-    @Qualifier("longVideoRedisTemplate")
-    private RedisTemplate<String, String> longVideoRedisTemplate;
-
-    @Resource
-    private WxVideoTagRelRepository wxVideoTagRelRepository;
-
-    @ApolloJsonValue("${content.security.generalization.user.condition.config:{}}")
-    private Map<String, GeneralizationUserConfig> generalizationUserConditionConfig;
-
-    /**
-     * 不同类型的用户要过滤掉的标签列表配置
-     * <br >
-     * <p>
-     * Key的格式为: {userType}:{userSubType}
-     * <br>
-     * userType枚举值: 1-竞品用户, 2-微信人员, 3-网安
-     * <br >
-     * userSubType枚举值: 1-精准用户, 2-泛化用户
-     */
-    @ApolloJsonValue("${content.security.filter.config:{}}")
-    private Map<String, TagFilterConfig> tagFilterConfigMap;
-
-    @Value("${aliyun.log.endpoint}")
-    private String endpoint;
-    @Value("${aliyun.log.accessKeyId}")
-    private String accessKeyId;
-    @Value("${aliyun.log.accessKeySecret}")
-    private String accessKeySecret;
-
-    @Value("${aliyun.blacklist.filter.log.project}")
-    private String project;
-    @Value("${aliyun.blacklist.filter.log.store}")
-    private String logStore;
-    @Value("${spring.profiles.active}")
-    private String activeProfile;
-    private Producer producer;
-
-    /**
-     * 保存Tag标签与视频列表的映射
-     * <br>
-     * Key为TagId,  Value为对应的视频ID列表
-     */
-    private static Map<Long, Set<Long>> videoTagCache = new ConcurrentHashMap<>();
-
-    /**
-     * 黑名单本地二级缓存,一级缓存为Redis缓存。此处直接读取即可
-     * <br />
-     * Redis缓存由longvideo服务写入
-     * <br>
-     * com.weiqu.video.service.filter.impl.BlacklistFilterImpl#refreshUidCache
-     * <br>
-     * com.weiqu.video.service.filter.impl.BlacklistFilterImpl#refreshIPCache
-     */
-    private final LoadingCache<String, Map<String, String>> blacklistCache = CacheBuilder.newBuilder()
-            .expireAfterWrite(5, TimeUnit.MINUTES)
-            .build(new CacheLoader<String, Map<String, String>>() {
-                @Override
-                public Map<String, String> load(@Nonnull String key) {
-                    Map<Object, Object> map = longVideoRedisTemplate.opsForHash().entries(key);
-                    if (MapUtils.isEmpty(map)) {
-                        return new HashMap<>();
-                    }
-                    return map.entrySet().stream().collect(
-                            Collectors.toMap(
-                                    entry -> entry.getKey().toString(),
-                                    entry -> entry.getValue().toString(),
-                                    (v1, v2) -> v1
-                            ));
-                }
-            });
-
-    @PostConstruct
-    public void init() {
-        LOG.info("generalizationUserConditionConfig: {}", generalizationUserConditionConfig);
-        LOG.info("tagFilterConfigMap: {}", tagFilterConfigMap);
-        refreshVideoTagCache();
-        initLogProducer();
-    }
-
-    @Scheduled(cron = "0 0/5 * * * ? ")
-    public void cronSync() {
-        refreshVideoTagCache();
-    }
-
-    private void initLogProducer() {
-        LOG.info("BlacklistContainer.initLogProducer: project={}, endpoint={}, accessKeyId={}, accessKeySecret={}, logStore={}",
-                project, endpoint, accessKeyId, accessKeySecret, logStore);
-        ProducerConfig producerConfig = new ProducerConfig();
-        producer = new LogProducer(producerConfig);
-        producer.putProjectConfig(new ProjectConfig(project, endpoint, accessKeyId, accessKeySecret));
-    }
-
-    public void refreshVideoTagCache() {
-        // LOG.info("同步本地标签ID与视频列表的缓存任务开始");
-        Map<Long, Set<Long>> tmpMap = new ConcurrentHashMap<>();
-
-        if (MapUtils.isNotEmpty(tagFilterConfigMap)) {
-
-            // 获取所有的标签ID列表
-            Set<Long> tagIdSet = new HashSet<>();
-            for (Map.Entry<String, TagFilterConfig> entry : tagFilterConfigMap.entrySet()) {
-                TagFilterConfig tagFilterConfig = entry.getValue();
-                if (Objects.isNull(tagFilterConfig)) {
-                    continue;
-                }
-                if (CollectionUtils.isNotEmpty(tagFilterConfig.getRecommendExcludeTag())) {
-                    tagIdSet.addAll(tagFilterConfig.getRecommendExcludeTag());
-                }
-                if (CollectionUtils.isNotEmpty(tagFilterConfig.getDetailExcludeTag())) {
-                    tagIdSet.addAll(tagFilterConfig.getDetailExcludeTag());
-                }
-            }
-
-            // 获取标签ID对应的视频ID列表
-            for (Long tagId : tagIdSet) {
-                List<WxVideoTagRel> wxVideoTagRels = wxVideoTagRelRepository.findAllByTagId(tagId);
-                Set<Long> videoIdSet = wxVideoTagRels.stream().map(WxVideoTagRel::getVideoId).collect(Collectors.toSet());
-                // LOG.info("同步本地标签ID与视频列表缓存任务 -- tagId: {}, videoIdSize: {}", tagId, videoIdSet.size());
-                tmpMap.put(tagId, videoIdSet);
-            }
-        }
-        videoTagCache = tmpMap;
-
-        // LOG.info("同步本地标签ID与视频列表的缓存任务结束");
-    }
-
-    public List<Long> filterUnsafeVideoByUser(List<Long> videoIds, String uid, Long hotSceneType, String cityCode, String clientIP, String mid, String usedScene, Integer appType) {
-        if (CollectionUtils.isEmpty(videoIds)) {
-            return videoIds;
-        }
-
-        String userType = this.matchUserBlacklistTypeEnum(uid, hotSceneType, cityCode, clientIP, mid, usedScene, appType);
-        Collection<Long> tagIdSet = this.findRecommendExcludeTagIds(userType, appType);
-        if (CollectionUtils.isEmpty(tagIdSet)) {
-            return videoIds;
-        }
-
-        return videoIds.stream().filter(videoId -> {
-            if (videoTagAnyMatch(videoId, tagIdSet)) {
-                // LOG.info("用户 {} 在因命中 {} 移除对应的视频ID {}: 请求参数为: hotSceneType={}, cityCode={}, clientIP={}, mid={}, usedScene={}, appType={}",
-                //         uid, userType, videoId, hotSceneType, cityCode, clientIP, mid, usedScene, appType);
-                return false;
-            }
-            return true;
-        }).collect(Collectors.toList());
-    }
-
-    public String matchUserBlacklistTypeEnum(String uid, Long hotSceneType, String cityCode, String clientIP, String mid,
-                                             String usedScene, Integer appType) {
-        try {
-            // LOG.info("计算用户黑名单类型,判断参数: uid={}, hotSceneType={}, cityCode={}, clientIP={}, mid={}, usedScene={}, appType={}",
-            //         uid, hotSceneType, cityCode, clientIP, mid, usedScene, appType);
-            if (StringUtils.isNotBlank(uid)) {
-                String key = this.calcUserRedisKey(uid);
-                Map<String, String> uidBlacklistMap = blacklistCache.get(key);
-                if (uidBlacklistMap.containsKey(uid)) {
-                    String userType = uidBlacklistMap.get(uid);
-                    this.filterLogUpload(uid, cityCode, hotSceneType, clientIP, userType, "UID", mid, usedScene, appType);
-                    // LOG.info("用户 {} 在UID黑名单中命中 {}", uid, userType);
-                    return userType;
-                }
-            }
-
-            if (StringUtils.isNotBlank(clientIP)) {
-                Map<String, String> ipBlacklistMap = blacklistCache.get(IP_VISIO_BLACKLIST_HASH_KEY);
-                if (ipBlacklistMap.containsKey(clientIP)) {
-                    String userType = ipBlacklistMap.get(clientIP);
-                    this.filterLogUpload(uid, cityCode, hotSceneType, clientIP, userType, "IP", mid, usedScene, appType);
-                    // LOG.info("用户 {} 在IP黑名单中命中 {}, 参数为: clientIP为: {}", uid, userType, clientIP);
-                    return userType;
-                }
-            }
-
-
-            String userType = this.matchGeneralizationUserType(uid, cityCode, hotSceneType, appType);
-            if (StringUtils.isNotBlank(userType)) {
-                this.filterLogUpload(uid, cityCode, hotSceneType, clientIP, userType, "RegionAndHotSceneType", mid, usedScene, appType);
-            }
-            return userType;
-        } catch (
-                Exception e) {
-            LOG.error("blacklist filter isSafeVideoByUid error: ", e);
-
-        }
-        return null;
-    }
-
-    private String matchGeneralizationUserType(String uid, String cityCode, Long hotSceneType, Integer appType) {
-        // 参数为空,则跳过
-        if (StringUtils.isBlank(cityCode) && Objects.isNull(appType)) {
-            return null;
-        }
-        // 配置为空,则跳过
-        if (MapUtils.isEmpty(generalizationUserConditionConfig)) {
-            return null;
-        }
-
-        // 优先找,城市+appType的配置
-        if (StringUtils.isNotBlank(cityCode) && Objects.nonNull(appType)) {
-            GeneralizationUserConfig userConfig = generalizationUserConditionConfig.get(cityCode + CONNECTOR_STR + appType);
-            if (Objects.nonNull(userConfig) && userConfig.isExcludeHotSceneType(hotSceneType)) {
-                // LOG.info("用户 {} 在泛化用户规则中命中: {}, 参数为: appType = {}, cityCode={}, hotSceneType={}", uid, userConfig.fullUserType, appType, cityCode, hotSceneType);
-                return userConfig.getFullUserType();
-            }
-        }
-
-        // 其次找,appType的配置
-        if (Objects.nonNull(appType)) {
-            GeneralizationUserConfig userConfig = generalizationUserConditionConfig.get(appType.toString());
-            if (Objects.nonNull(userConfig) && userConfig.isExcludeHotSceneType(hotSceneType)) {
-                // LOG.info("用户 {} 在泛化用户规则中命中: {}, 参数为: appType={}, hotSceneType={}", uid, userConfig.fullUserType, appType, hotSceneType);
-                return userConfig.getFullUserType();
-            }
-        }
-
-        // 最后找,城市的配置
-        if (StringUtils.isNotBlank(cityCode)) {
-            GeneralizationUserConfig userConfig = generalizationUserConditionConfig.get(cityCode);
-            if (Objects.nonNull(userConfig) && userConfig.isExcludeHotSceneType(hotSceneType)) {
-                // LOG.info("用户 {} 在泛化用户规则中命中: {}, 参数为: cityCode={}, hotSceneType={}", uid, userConfig.fullUserType, cityCode, hotSceneType);
-                return userConfig.getFullUserType();
-            }
-        }
-        return null;
-    }
-
-    /**
-     * 匹配videoId的标签包含tagIds中的任意一个
-     *
-     * @param videoId 视频ID
-     * @param tagIds  标签ID列表
-     * @return true-匹配,false-不匹配
-     */
-    private boolean videoTagAnyMatch(Long videoId, Collection<Long> tagIds) {
-        if (MapUtils.isEmpty(videoTagCache) || CollectionUtils.isEmpty(tagIds)) {
-            return false;
-        }
-        for (Long tagId : tagIds) {
-            Set<Long> videoIds = videoTagCache.get(tagId);
-            if (CollectionUtils.isNotEmpty(videoIds) && videoIds.contains(videoId)) {
-                return true;
-            }
-        }
-
-        return false;
-    }
-
-    private String calcUserRedisKey(String uidStr) {
-        long uid = 0L;
-        try {
-            uid = Long.parseLong(uidStr);
-        } catch (
-                Exception ignore) {
-        }
-        return USER_VISIO_BLACKLIST_HASH_KEY + (uid % USER_REDIS_KEY_PARTITION_COUNT);
-    }
-
-    private Collection<Long> findRecommendExcludeTagIds(String userType, Integer appType) {
-        if (StringUtils.isBlank(userType) || MapUtils.isEmpty(tagFilterConfigMap)) {
-            return Collections.emptySet();
-        }
-
-        // 查看单APP配置的
-        if (StringUtils.isNotBlank(userType) && Objects.nonNull(appType)) {
-            String key = userType + CONNECTOR_STR + appType;
-            TagFilterConfig tagFilterConfig = tagFilterConfigMap.get(key);
-            if (Objects.nonNull(tagFilterConfig)) {
-                // LOG.info("命中过滤标签配置: {} == {}", key, tagFilterConfig.getRecommendExcludeTag());
-                return tagFilterConfig.getRecommendExcludeTag();
-            }
-        }
-
-        if (StringUtils.isNotBlank(userType)) {
-            TagFilterConfig tagFilterConfig = tagFilterConfigMap.get(userType);
-            if (Objects.nonNull(tagFilterConfig)) {
-                // LOG.info("命中过滤标签配置: {} == {}", userType, tagFilterConfig.getRecommendExcludeTag());
-                return tagFilterConfig.getRecommendExcludeTag();
-            }
-        }
-        return null;
-    }
-
-    private void filterLogUpload(String uid, String cityCode, Long hotSceneType, String clientIp, String fullUserType, String blacklistType, String mid, String usedScene, Integer appType) {
-        try {
-            String[] split = fullUserType.split(CONNECTOR_STR);
-            Map<String, String> logMap = new HashMap<>();
-            logMap.put("uid", StringUtils.isNotBlank(uid) ? uid : "");
-            logMap.put("mid", StringUtils.isNotBlank(mid) ? mid : "");
-            logMap.put("cityCode", StringUtils.isNotBlank(cityCode) ? cityCode : "");
-            logMap.put("hotSceneType", Objects.nonNull(hotSceneType) ? hotSceneType.toString() : "");
-            logMap.put("clientIp", StringUtils.isNotBlank(clientIp) ? clientIp : "");
-            logMap.put("usedScene", StringUtils.isNotBlank(usedScene) ? usedScene : "");
-            logMap.put("appType", Objects.nonNull(appType) ? appType.toString() : "");
-            logMap.put("userType", split[0]);
-            logMap.put("userSubType", split[1]);
-            logMap.put("env", activeProfile);
-            logMap.put("blacklistType", blacklistType);
-            logMap.put("uploadService", "recommend-server");
-
-            LogItem logItem = new LogItem();
-            logMap.forEach(logItem::PushBack);
-
-            ThreadPoolFactory.logPool().execute(() -> {
-                try {
-                    producer.send(project, logStore, logItem);
-                } catch (
-                        Exception e) {
-                    LOG.error("log send error: ", e);
-                }
-            });
-        } catch (
-                Exception e) {
-            LOG.error("blacklist filter upload log error: ", e);
-        }
-    }
-
-    @Data
-    private static class GeneralizationUserConfig {
-        Set<Long> excludeHotSceneType;
-        String userType;
-        String userSubType;
-        String fullUserType;
-
-        public boolean isExcludeHotSceneType(Long hotSceneType) {
-            return CollectionUtils.isEmpty(excludeHotSceneType)
-                    || !excludeHotSceneType.contains(hotSceneType);
-        }
-
-    }
-
-    @Data
-    private static class TagFilterConfig {
-        /**
-         * 推荐场景下要过滤掉的标签
-         */
-        Set<Long> recommendExcludeTag;
-        /**
-         * 详情场景下要过滤掉的标签
-         */
-        Set<Long> detailExcludeTag;
-
-    }
-
-}

+ 0 - 125
recommend-server-service/src/main/java/com/tzld/piaoquan/recommend/server/service/filter/strategy/SecurityStrategy.java

@@ -1,125 +0,0 @@
-package com.tzld.piaoquan.recommend.server.service.filter.strategy;
-
-import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue;
-import com.google.common.cache.CacheBuilder;
-import com.google.common.cache.CacheLoader;
-import com.google.common.cache.LoadingCache;
-import com.tzld.piaoquan.recommend.server.repository.WxVideoTagRel;
-import com.tzld.piaoquan.recommend.server.repository.WxVideoTagRelRepository;
-import com.tzld.piaoquan.recommend.server.service.filter.FilterParam;
-import com.tzld.piaoquan.recommend.server.service.filter.FilterStrategy;
-import com.tzld.piaoquan.recommend.server.util.CommonCollectionUtils;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.collections4.CollectionUtils;
-import org.apache.commons.collections4.MapUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.PostConstruct;
-import javax.annotation.Resource;
-import java.util.*;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
-
-/**
- * @author dyp
- */
-@Component
-@Slf4j
-public class SecurityStrategy implements FilterStrategy {
-    @Value("#{'${block.hotscenetype.list:}'.split(',')}")
-    private Set<Long> excludeScenes;
-    @ApolloJsonValue("${video.filter.city.tagid.json:{}}")
-    private Map<String, List<Long>> videoFilterCityTagIdMap;
-    @Value("${securityAbExpCode:625}")
-    private String securityAbExpCode;
-    @Value("${securityGlobalSwitch:false}")
-    private boolean securityGlobalSwitch;
-
-    @Value("${content.security.new.filter.switch:false}")
-    private boolean newContentSecurityFilterSwitch;
-
-    @Autowired
-    private WxVideoTagRelRepository wxVideoTagRelRepository;
-
-    @Resource
-    private BlacklistContainer blacklistContainer;
-
-    // 内存持久保存不淘汰
-    private LoadingCache<String, Set<Long>> videoCache = CacheBuilder.newBuilder()
-            .maximumSize(100)
-            .refreshAfterWrite(60, TimeUnit.SECONDS)
-            .expireAfterWrite(60, TimeUnit.SECONDS)
-            .expireAfterAccess(60, TimeUnit.SECONDS)
-            .build(new CacheLoader<String, Set<Long>>() {
-                @Override
-                public Set<Long> load(String cityCode) {
-                    if (MapUtils.isEmpty(videoFilterCityTagIdMap)) {
-                        return new HashSet<>();
-                    }
-                    List<Long> tagIds = videoFilterCityTagIdMap.get(cityCode);
-                    if (CollectionUtils.isEmpty(tagIds)) {
-                        return new HashSet<>();
-                    }
-                    List<WxVideoTagRel> rels = wxVideoTagRelRepository.findAllByTagIdIn(tagIds);
-                    return CommonCollectionUtils.toSet(rels, WxVideoTagRel::getVideoId);
-                }
-            });
-
-    @PostConstruct
-    public void init() {
-        if (MapUtils.isEmpty(videoFilterCityTagIdMap)) {
-            return;
-        }
-        for (String cityCode : videoFilterCityTagIdMap.keySet()) {
-            videoCache.getUnchecked(cityCode);
-        }
-        log.info("newContentSecurityFilterSwitch: {}", newContentSecurityFilterSwitch);
-    }
-
-    @Override
-    public List<Long> filter(FilterParam param) {
-
-        if (param == null) {
-            return Collections.emptyList();
-        }
-        if (CollectionUtils.isEmpty(param.getVideoIds())) {
-            return param.getVideoIds();
-        }
-
-        boolean hit = securityGlobalSwitch
-                || CommonCollectionUtils.contains(param.getAbExpCodes(), securityAbExpCode);
-        if (!hit) {
-            return param.getVideoIds();
-        }
-
-        if (newContentSecurityFilterSwitch) {
-            return blacklistContainer.filterUnsafeVideoByUser(param.getVideoIds(), param.getUid(), param.getHotSceneType(),
-                    param.getCityCode(), param.getClientIp(), param.getMid(), "recommend", param.getAppType());
-        }
-
-        if (CollectionUtils.isEmpty(excludeScenes)
-                || !CommonCollectionUtils.contains(excludeScenes, param.getHotSceneType())) {
-            log.info("old filter cityCodeAndScene filter");
-            if (MapUtils.isEmpty(videoFilterCityTagIdMap)
-                    || !videoFilterCityTagIdMap.containsKey(param.getCityCode())) {
-                return param.getVideoIds();
-            }
-
-            Set<Long> filterVideos = videoCache.getUnchecked(param.getCityCode());
-            if (CollectionUtils.isEmpty(filterVideos)) {
-                return param.getVideoIds();
-            }
-
-            List<Long> result = param.getVideoIds().stream()
-                    .filter(l -> !filterVideos.contains(l))
-                    .collect(Collectors.toList());
-
-            return result;
-        }
-        return param.getVideoIds();
-
-
-    }
-}

+ 1 - 20
recommend-server-service/src/main/java/com/tzld/piaoquan/recommend/server/service/recall/RecallService.java

@@ -2,16 +2,11 @@ package com.tzld.piaoquan.recommend.server.service.recall;
 
 import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue;
 import com.tzld.piaoquan.recommend.server.common.ThreadPoolFactory;
-import com.tzld.piaoquan.recommend.server.common.base.Constant;
 import com.tzld.piaoquan.recommend.server.common.enums.AppTypeEnum;
 import com.tzld.piaoquan.recommend.server.model.Video;
-import com.tzld.piaoquan.recommend.server.service.filter.strategy.BlacklistContainer;
 import com.tzld.piaoquan.recommend.server.service.flowpool.FlowPoolConstants;
 import com.tzld.piaoquan.recommend.server.service.recall.strategy.*;
-import com.tzld.piaoquan.recommend.server.util.CommonCollectionUtils;
-import com.tzld.piaoquan.recommend.server.util.JSONUtils;
 import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.BeansException;
 import org.springframework.context.ApplicationContext;
@@ -19,7 +14,6 @@ import org.springframework.context.ApplicationContextAware;
 import org.springframework.stereotype.Service;
 
 import javax.annotation.PostConstruct;
-import javax.annotation.Resource;
 import java.util.*;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.ExecutorService;
@@ -38,14 +32,6 @@ public class RecallService implements ApplicationContextAware {
     private final ExecutorService pool = ThreadPoolFactory.recallPool();
     @ApolloJsonValue("${alg.recall.special.app&vid:{}}")
     protected Map<String, List<Long>> specialAppVid;
-    @Resource
-    private BlacklistContainer blacklistContainer;
-
-    /**
-     * 在流量池场景下,哪些appType用判断黑名单
-     */
-    @ApolloJsonValue("${content.security.recommendflowpool.blacklist.apptype.config:[]}")
-    private Set<Integer> blacklistAppTypeSet;
 
     @PostConstruct
     public void init() {
@@ -101,11 +87,6 @@ public class RecallService implements ApplicationContextAware {
             return strategies;
         }
 
-        String matchUserBlacklistTypeEnum = blacklistContainer.matchUserBlacklistTypeEnum(param.getUid(), param.getHotSceneType(), param.getCityCode(),
-                param.getClientIp(), param.getMid(), "recommend-flow-pool", param.getAppType());
-        boolean hitUserBlacklist = StringUtils.isNotBlank(matchUserBlacklistTypeEnum);
-        boolean isInBlacklist = CollectionUtils.isNotEmpty(blacklistAppTypeSet) && blacklistAppTypeSet.contains(param.getAppType());
-
         String abCode = param.getAbCode();
         //1:通过“产品”控制“召回子策略”. 票圈美好祝福与内部tab只走祝福召回。APP只走固定列表。特殊配置的app只有固定召回列表。
         if (this.matchSpecialApp(param.getAppType())) {
@@ -147,7 +128,7 @@ public class RecallService implements ApplicationContextAware {
                 strategies.addAll(getRegionRecallStrategy(param));
         }
         // 命中用户黑名单不走流量池
-        if (!param.isRiskUser() && (!hitUserBlacklist || !isInBlacklist)) {
+        if (!param.isRiskUser()) {
             if (param.getFlowPoolAbtestGroup().equals(FlowPoolConstants.EXPERIMENTAL_FLOW_SET_LEVEL)) {
                 strategies.add(strategyMap.get(FlowPoolWithLevelRecallStrategyTomson.class.getSimpleName()));
             } else if (param.getFlowPoolAbtestGroup().equals(FlowPoolConstants.EXPERIMENTAL_FLOW_SET_LEVEL_SCORE)) {