探花交友10-数据统计与内容审核

从SPICE到电磁场:非线性器件在CST场路协同仿真中的建模艺术 本文深入探讨了非线性器件在CST场路协同仿真中的建模技术,重点分析了SPICE模型与电磁场仿真的集成方法。通过对比线电流模型和面电流模型的优缺点,结合实际案例展示了二极管阵列在电磁散射调控中的应用,为工程师提供了优化仿真精度与效率的实用技巧。 阅读详情

1、用户冻结解冻

用户冻结/解冻使用管理员在后台系统对用户的惩罚措施。对于发布不当言论或者违法违规内容的用户,可以暂时、永久禁止其登录,评论,发布动态、

后台中解冻/冻结,就是将用户状态写入数据库中

APP端用户在进行登录,评论,发布动态时检测Redis中冻结状态
在这里插入图片描述

1.1 用户冻结

ManageController
//用户冻结
@PostMapping("/users/freeze")
public ResponseEntity freeze(@RequestBody Map params) {
    Map map =  managerService.userFreeze(params);
    return ResponseEntity.ok(map);
}
ManageService
//用户冻结
public Map userFreeze(Map params) {
    Integer freezingTime = (Integer) params.get("freezingTime");
    Long userId = (Long) params.get("userId");
    int days = 0;
    if (freezingTime == 1) {
        days = 3;
    }
    if (freezingTime == 2) {
        days = 7;
    }
    if (freezingTime == 3) {
        days = -1;
    }
    String value = JSON.toJSONString(params);
    redisTemplate.opsForValue().set(Constants.FREEZE_USER+userId,value,days, TimeUnit.MINUTES);
    Map map = new HashMap();
    map.put("message","冻结成功");
    return map;
}

1.2 用户解冻

ManageController
//用户解冻
@PostMapping("/users/unfreeze")
public ResponseEntity unfreeze(@RequestBody  Map params) {
    Map map =  managerService.userUnfreeze(params);
    return ResponseEntity.ok(map);
}
ManageService
//用户解冻
public Map userUnfreeze(Map params) {
    Long userId = (Long) params.get("userId");
    String reasonsForThawing = (String) params.get("reasonsForThawing");
    redisTemplate.delete(Constants.FREEZE_USER+userId);
    Map map = new HashMap();
    map.put("message","解冻成功");
    return map;
}

1.3 查询数据列表

UserInfo

添加字段

//用户状态,1为正常,2为冻结
@TableField(exist = false)
private String userStatus = "1";
ManageService
public ResponseEntity findById(Long userId) {
    UserInfo info = userInfoApi.findById(userId);
    if(redisTemplate.hasKey(Constants.FREEZE_USER+info.getId())) {
        info.setUserStatus("2");
    }
    return ResponseEntity.ok(info);
}
1.4 探花系统修改
UserFreezeService
@Service
public class UserFreezeService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public void checkUserStatus(Integer state,Long userId) {
        String value = redisTemplate.opsForValue().get(Constants.FREEZE_USER + userId);
        if(!StringUtils.isEmpty(value)) {
            Map map = JSON.parseObject(value, Map.class);
            Integer freezingRange = (Integer) map.get("freezingRange");
            if(freezingRange == state) {
                throw new BusinessException(ErrorResult.builder().errMessage("您的账号被冻结!").build());
            }
        }
    }
}

2、数据统计

后台系统首页中,显示各种统计数据,比如:累计用户数、新增用户数、登录次数等内容。

1、探花系统将用户操作日志写入RabbitMQ

2、管理后台获取最新消息,构造日志数据存入数据库

3、加入统计表,定时统计
在这里插入图片描述

2.1 数据采集

1、探花系统将用户操作日志写入RabbitMQ

2、管理后台获取最新消息,构造日志数据存入数据库

2.1.1 部署RabbitMQ

探花交友所需的第三方服务组件,已经以Docker-Compose准备好了。仅仅需要进入相关目录,以命令形式启动运行即可

#进入目录
cd /root/docker-file/rmq/
#创建容器并启动
docker-compose up –d
#查看容器
docker ps -a

服务地址:192.168.136.160:5672

管理后台:http://192.168.136.160:15672/

2.1.2 消息类型说明

探花项目间使用RabbitMQ收发消息,这里采用topic类型消息

日志消息key规则:log.xxx
在这里插入图片描述

2.1.3 实体类对象
Log
package com.tanhua.model.domain;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Log {
    /**
     * id
     */
    private Long id;
    /**
     * 用户id
     */
    private Long userId;
    /**
     * 操作时间
     */
    private String logTime;

    /**
     * 操作类型,
     * 0101为登录,0102为注册,
     * 0201为发动态,0202为浏览动态,0203为动态点赞,0204为动态喜欢,0205为评论,0206为动态取消点赞,0207为动态取消喜欢,
     * 0301为发小视频,0302为小视频点赞,0303为小视频取消点赞,0304为小视频评论
     */
    private String type;

    /**
     * 登陆地点
     */
    private String place;
    /**
     * 登陆设备
     */
    private String equipment;

    public Log(Long userId, String logTime, String type) {
        this.userId = userId;
        this.logTime = logTime;
        this.type = type;
    }
}
Analysis
package com.tanhua.model.domain;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Analysis{

    private Long id;
    /**
     * 日期
     */
    private Date recordDate;
    /**
     * 新注册用户数
     */
    private Integer numRegistered = 0;
    /**
     * 活跃用户数
     */
    private Integer numActive = 0;
    /**
     * 登陆次数
     */
    private Integer numLogin = 0;
    /**
     * 次日留存用户数
     */
    private Integer numRetention1d = 0;

    private Date created;
}
2.1.4 发送日志消息
@Autowired
private AmqpTemplate amqpTemplate;
public void login() {
    ………    
    //构造Map集合   
    Map<String, Object> msg = new HashMap<>();   
    msg.put(“userId”, UserHolder.getUserId().toString());  
    msg.put(“date", System.currentTimeMillis());    
	msg.put("type", "0101",);   
    String message = JSON.toJSONString(msg);    
    //发送消息
 	try {      
		amqpTemplate.convertSendAndReceive("tanhua.log.exchange",
                                             "log.user",message);    
	}catch (Exception e) {
		e.printStackTrace();
	}  
	………
}
2.1.5 监听器处理消息
@Component
public class LogListener {

    @Autowired
    private LogMapper logMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(
                    value = "tanhua.log.queue",
                    durable = "true"
            ),
            exchange = @Exchange(
                    value = "tanhua.log.exchange",
                    type = ExchangeTypes.TOPIC),
            key = {"log.*"})
    )
    public void listenCreate(String message) throws Exception {
        try {
            Map<String, Object> map = JSON.parseObject(message);
            //1、获取数据
            Long userId = (Long) map.get("userId");
            String date = (String) map.get("date");
            String objId = (String) map.get("objId");
            String type = (String) map.get("type");
            //2、保存到数据库
            Log log = new Log(userId,date,type);
            logMapper.insert(log);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
2.1.6 消息发送工具类
package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class MqMessageService {

    @Autowired
    private AmqpTemplate amqpTemplate;

    //发送日志消息
    public void sendLogService(Long userId,String type,String key,String busId) {
        try {
            Map map = new HashMap();
            map.put("userId",userId.toString());
            map.put("type",type);
            map.put("logTime",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            map.put("busId",busId);
            String message = JSON.toJSONString(map);
            amqpTemplate.convertAndSend("tanhua.log.exchange",
                    "log."+key,message);
        } catch (AmqpException e) {
            e.printStackTrace();
        }
    }

    //发送动态审核消息
    public void sendAudiService(String movementId) {
        try {
            amqpTemplate.convertAndSend("tanhua.audit.exchange",
                    "audit.movement",movementId);
        } catch (AmqpException e) {
            e.printStackTrace();
        }
    }
}

2.2 AOP处理日志

项目中大量方法需要改造,加入消息处理。

不易维护且存在耦合

解决方法:使用AOP + 自定义注解

2.2.1 自定义注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogConfig {

    //动态获取方法参数,支持SpringEL
    String objId() default "";

    //路由的key
    String key();

    //日志类型
    String type();
}
2.2.2 切面
@Component
@Aspect
public class LogAspect {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Before(value="execution(* com.tanhua.server.service.*.*(..)) && @annotation(config)")
    public void checkUserState(JoinPoint pjp , LogConfig config) throws Throwable {
        //解析SpringEL获取动态参数
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        String objId = parse(config.objId(), signature.getParameterNames(), pjp.getArgs());
        //构造Map集合
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", UserHolder.getUserId());
        msg.put("date", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        msg.put("objId", objId);
        msg.put("type", config.type());
        String message = JSON.toJSONString(msg);
        //发送消息
        try {
            amqpTemplate.convertSendAndReceive("tanhua.log.exchange",
                    "log."+config.key(),message);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }


    public String parse(String expression, String[] paraNames,Object [] paras) {
        if(StringUtils.isEmpty(expression)) return "";
        StandardEvaluationContext context = new StandardEvaluationContext();
        for(int i=0;i<paraNames.length;i++) {
            context.setVariable(paraNames[i], paras[i]);
        }
        Expression exp = new SpelExpressionParser().parseExpression(expression);
        Object value = exp.getValue(context);
        return value == null ? "" : value.toString();
    }
}
2.2.3 配置
//根据id查询
@LogConfig(type = "0202",key = "movement",objId = "#movementId")
public MovementsVo findById(String movementId) {
    //1、调用api根据id查询动态详情
    Movement movement = movementApi.findById(movementId);
    //2、转化vo对象
    if(movement != null) {
        UserInfo userInfo = userInfoApi.findById(movement.getUserId());
        return MovementsVo.init(userInfo,movement);
    }else {
        return null;
    }
}

2.3 定时任务

在实际项目开发中,除了Web应用、SOA服务外,还有一类不可缺少的,那就是定时任务调度。定时任务的场景可以说非常广泛:

  • 某些网站会定时发送优惠邮件;

  • 银行系统还款日信用卡催收款;

  • 某些应用的生日祝福短信等。

那究竟何为定时任务调度,一句话概括就是:基于给定的时间点、给定的时间间隔、自动执行的任务

2.3.1 入门案例
开启定时任务
@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@MapperScan("com.tanhua.admin.mapper")
@EnableScheduling //开启定时任务支持
public class AdminServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(AdminServerApplication.class,args);
    }
}
定时任务类
@Component
public class AnalysisTask {
    /**
     * 配置时间规则
     */
    @Scheduled( cron = "0/20 * * * * ? ")
    public void analysis() throws ParseException {
        //业务逻辑
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println("当前时间:"+time);
    }
}
2.3.2 CRON表达式

对于定时任务,我们使用的时候主要是注重两个方面,一个是定时任务的业务,另一个就是Cron表达式。

**Cron 表达式支持到六个域 **

名称是否必须允许值特殊字符
秒是0-59, - * /
分是0-59, - * /
时是0-23, - * /
日是1-31, - * ? / L W C
月是1-12 或 JAN-DEC, - * /
周是1-7 或 SUN-SAT, - * ? / L C #

月份和星期的名称是不区分大小写的。FRI 和 fri 是一样的。 域之间有空格分隔

2.3.3 定时统计
AnalysisTask
@Component
public class AnalysisTask {

    @Autowired
    private AnalysisService analysisService;

    /**
     * 配置时间规则
     */
    @Scheduled( cron = "0/20 * * * * ? ")
    public void analysis() throws ParseException {
        //业务逻辑
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println("开始统计:"+time);
        //调logService完成日志统计
        analysisService.analysis();
        System.out.println("结束统计");
    }
}
AnalysisService
/**
 * 定时统计日志数据到统计表中
 *    1、查询tb_log表中的数 (每日注册用户数,每日登陆用户,活跃的用户数据,次日留存的用户)
 *    2、构造AnalysisByDay对象
 *    3、完成统计数据的更新或者保存
 */
public void analysis() throws ParseException {

    String todayStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    String yestodayStr =  DateUtil.yesterday().toString("yyyy-MM-dd"); //工具类
    //1、统计每日注册用户数
    Integer numRegistered = logMapper.queryByTypeAndLogTime("0102",todayStr);
    //2、统计每日登陆用户
    Integer numLogin = logMapper.queryByTypeAndLogTime("0101",todayStr);
    //3、统计活跃的用户数
    Integer numActive = logMapper.queryByLogTime(todayStr);
    //4、统计次日留存的用户数
    Integer numRetention1d = logMapper.queryNumRetention1d(todayStr, yestodayStr);
    //5、根据当前时间查询AnalysisByDay数据
    QueryWrapper<Analysis> qw = new QueryWrapper<>();
    Date todatDate = new SimpleDateFormat("yyyy-MM-dd").parse(todayStr);
    qw.eq("record_date", todatDate);

    Analysis analysis = analysisMapper.selectOne(qw);
    if(analysis == null) {
        //7、如果不存在,保存
        analysis = new Analysis();
        analysis.setRecordDate(todatDate);
        analysis.setNumRegistered(numRegistered);
        analysis.setNumLogin(numLogin);
        analysis.setNumActive(numActive);
        analysis.setNumRetention1d(numRetention1d);
        analysis.setCreated(new Date());
        analysisMapper.insert(analysis);
    }else{
        //8、如果存在,更新
        analysis.setNumRegistered(numRegistered);
        analysis.setNumLogin(numLogin);
        analysis.setNumActive(numActive);
        analysis.setNumRetention1d(numRetention1d);
        analysisMapper.updateById(analysis);
    }

}
AnalysisMapper
public interface LogMapper extends BaseMapper<Log> {
    @Select("SELECT COUNT(DISTINCT user_id) FROM tb_log WHERE TYPE=#{type} AND log_time=#{logTime}")
    Integer queryByTypeAndLogTime(@Param("type") String type, @Param("logTime") String logTime); //根据操作时间和类型


    @Select("SELECT COUNT(DISTINCT user_id) FROM tb_log WHERE log_time=#{logTime}")
    Integer queryByLogTime(String logTime); //展示记录时间查询


    @Select("SELECT COUNT(DISTINCT user_id)  FROM tb_log WHERE log_time=#{today} AND user_id IN (\n " +
        " SELECT user_id FROM tb_log WHERE TYPE=\"0102\" AND log_time=#{yestoday} \n " +
        ")")
    Integer queryNumRetention1d(@Param("today")  String today,@Param("yestoday") String yestoday); //查询次日留存
}
测试数据

为了方便操作,可以通过以下单元测试方法。保存若干操作数据

package com.tanhua.manager.test;

import com.tanhua.manager.domain.Log;
import com.tanhua.manager.mapper.LogMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Random;

@RunWith(SpringRunner.class)
@SpringBootTest
public class LogTest {

    @Autowired
    private LogMapper logMapper;
    
    private String logTime = "";

    //模拟登录数据
    public void testInsertLoginLog() {
        for (int i = 0; i < 5; i++) {
            Log log = new Log();
            log.setUserId((long)(i+1));
            log.setLogTime(logTime);
            log.setType("0101");
            logMapper.insert(log);
        }
    }

    //模拟注册数据
    public void testInsertRegistLog() {
        for (int i = 0; i < 10; i++) {
            Log log = new Log();
            log.setUserId((long)(i+1));
            log.setLogTime(logTime);
            log.setType("0102");
            logMapper.insert(log);
        }
    }
    //模拟其他操作
    public void testInsertOtherLog() {
        String[] types = new String[]{"0201","0202","0203","0204","0205","0206","0207","0301","0302","0303","0304"};
        for (int i = 0; i < 10; i++) {
            Log log = new Log();
            log.setUserId((long)(i+1));
            log.setLogTime(logTime);
            int index = new Random().nextInt(10);
            log.setType(types[index]);
            logMapper.insert(log);
        }
    }

	@Test
    public void generData() {
        testInsertLoginLog();
        testInsertRegistLog();
        testInsertOtherLog();
    }
}

2.4 首页统计

在这里插入图片描述

2.4.1 vo对象
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AnalysisSummaryVo {
    /**
     * 累计用户数
     */
    private Long cumulativeUsers;
    /**
     * 过去30天活跃用户数
     */
    private Long activePassMonth;
    /**
     * 过去7天活跃用户
     */
    private Long activePassWeek;
    /**
     * 今日新增用户数量
     */
    private Long newUsersToday;
    /**
     * 今日新增用户涨跌率,单位百分数,正数为涨,负数为跌
     */
    private BigDecimal newUsersTodayRate;
    /**
     * 今日登录次数
     */
    private Long loginTimesToday;
    /**
     * 今日登录次数涨跌率,单位百分数,正数为涨,负数为跌
     */
    private BigDecimal loginTimesTodayRate;
    /**
     * 今日活跃用户数量
     */
    private Long activeUsersToday;
    /**
     * 今日活跃用户涨跌率,单位百分数,正数为涨,负数为跌
     */
    private BigDecimal activeUsersTodayRate;
}
2.4.2 DashboardController
@RestController
@RequestMapping("/dashboard")
public class DashboardController {

    @Autowired
    private AnalysisService analysisService;

    /**
     * 概要统计信息
     */
    @GetMapping("/dashboard/summary")
    public AnalysisSummaryVo getSummary() {

        AnalysisSummaryVo analysisSummaryVo = new AnalysisSummaryVo();

        DateTime dateTime = DateUtil.parseDate("2020-09-08");

        //累计用户数
        analysisSummaryVo.setCumulativeUsers(Long.valueOf(1000));

        //过去30天活跃用户
        analysisSummaryVo.setActivePassMonth(this.analysisService.queryActiveUserCount(dateTime, -30));

        //过去7天活跃用户
        analysisSummaryVo.setActivePassWeek(this.analysisService.queryActiveUserCount(dateTime, -7));

        //今日活跃用户
        analysisSummaryVo.setActiveUsersToday(this.analysisService.queryActiveUserCount(dateTime, 0));


        //今日新增用户
        analysisSummaryVo.setNewUsersToday(this.analysisService.queryRegisterUserCount(dateTime, 0));

        //今日新增用户涨跌率,单位百分数,正数为涨,负数为跌
        analysisSummaryVo.setNewUsersTodayRate(computeRate(
                analysisSummaryVo.getNewUsersToday(),
                this.analysisService.queryRegisterUserCount(dateTime, -1)
        ));

        //今日登录次数
        analysisSummaryVo.setLoginTimesToday(this.analysisService.queryLoginUserCount(dateTime, 0));

        //今日登录次数涨跌率,单位百分数,正数为涨,负数为跌
        analysisSummaryVo.setLoginTimesTodayRate(computeRate(
                analysisSummaryVo.getLoginTimesToday(),
                this.analysisService.queryLoginUserCount(dateTime, -1)
        ));


        return analysisSummaryVo;

    }

    private static BigDecimal computeRate(Long current, Long last) {
        BigDecimal result;
        if (last == 0) {
            // 当上一期计数为零时,此时环比增长为倍数增长
            result = new BigDecimal((current - last) * 100);
        } else {
            result = BigDecimal.valueOf((current - last) * 100).divide(BigDecimal.valueOf(last), 2, BigDecimal.ROUND_HALF_DOWN);
        }
        return result;
    }
    
    private static String offsetDay(Date date,int offSet) {
        return DateUtil.offsetDay(date,offSet).toDateStr();
    }
}
2.4.3 AnalysisService
/**
 * 查询活跃用户的数量
 */
public Long queryActiveUserCount(DateTime today, int offset) {
    return this.queryUserCount(today, offset, "num_active");
}

/**
 * 查询注册用户的数量
 */
public Long queryRegisterUserCount(DateTime today, int offset) {
    return this.queryUserCount(today, offset, "num_registered");
}

/**
 * 查询登录用户的数量
 */
public Long queryLoginUserCount(DateTime today, int offset) {
    return this.queryUserCount(today, offset, "num_login");
}

private Long queryAnalysisCount(String column,String today,String offset){
    return analysisMapper.sumAnalysisData(column,leDate,dtDate);
}
2.4.4 AnalysisMapper
public interface AnalysisMapper extends BaseMapper<Analysis> {

    @Select("select sum(${column}) from tb_analysis where record_date > #{leDate} and record_date < #{gtDate}")
    Long sumAnalysisData(@Param("column") String column, @Param("leDate") String leDate, @Param("gtDate") String gtDate);
}

3、内容审核

内容安全是识别服务,支持对图片、视频、文本、语音等对象进行多样化场景检测,有效降低内容违规风险。

目前很多平台都支持内容检测,如阿里云、腾讯云、百度AI、网易云等国内大型互联网公司都对外提供了API。

按照性能和收费来看,探花交友项目使用的就是阿里云的内容安全接口,使用到了图片和文本的审核。

3.1 阿里云内容审核

3.1.1 准备工作

1,前往阿里云官网注册账号

2,打开云盾内容安全产品试用页面,单击立即开通,正式开通服务
在这里插入图片描述

3,在AccessKey管理页面管理您的AccessKeyID和AccessKeySecret
在这里插入图片描述

3.1.2 文本内容垃圾检测

文本垃圾内容检测:点击访问

文本垃圾内容Java SDK: 点击访问
在这里插入图片描述

3.1.3 图片审核

在这里插入图片描述

图片垃圾内容Java SDK: https://help.aliyun.com/document_detail/53424.html?spm=a2c4g.11186623.6.715.c8f69b12ey35j4

3.1.4 抽取工具
GreenProperties
@Data
@ConfigurationProperties("tanhua.green")
public class GreenProperties {
    /**
     * 账号
     */
    String accessKeyID;
    /**
     * 密钥
     */
    String accessKeySecret;

    /**
     * 场景
     */
    String scenes;
}
AliyunGreenTemplate
package com.tanhua.autoconfig.template;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.green.model.v20180509.TextScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.tanhua.autoconfig.properties.GreenProperties;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * @author: itheima
 * @create: 2021-05-31 00:46
 */
@Slf4j
public class AliyunGreenTemplate {

    private IAcsClient client;

    private GreenProperties greenProperties;

    public AliyunGreenTemplate(GreenProperties greenProperties) {
        this.greenProperties = greenProperties;
        try {
            IClientProfile profile = DefaultProfile
                    .getProfile("cn-shanghai", greenProperties.getAccessKeyID(), greenProperties.getAccessKeySecret());
            DefaultProfile
                    .addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
            client = new DefaultAcsClient(profile);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Green配置缺失,请补充!");
        }
    }


    /**
     * 阿里云文本内容检查
     *
     * @param content
     * @return map  key - suggestion内容
     * pass:文本正常,可以直接放行,
     * review:文本需要进一步人工审核,
     * block:文本违规,可以直接删除或者限制公开
     * value -   通过,或 出错原因
     * @throws Exception
     */
    public Map<String, String> greenTextScan(String content) throws Exception {
        TextScanRequest textScanRequest = new TextScanRequest();
        textScanRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
        textScanRequest.setHttpContentType(FormatType.JSON);
        textScanRequest.setMethod(MethodType.POST); // 指定请求方法
        textScanRequest.setEncoding("UTF-8");
        textScanRequest.setRegionId("cn-shanghai");
        List<Map<String, Object>> tasks = new ArrayList<>();
        Map<String, Object> task1 = new LinkedHashMap<>();
        task1.put("dataId", UUID.randomUUID().toString());
        /**
         * 待检测的文本,长度不超过10000个字符
         */
        task1.put("content", content);
        tasks.add(task1);
        JSONObject data = new JSONObject();

        /**
         * 检测场景,文本垃圾检测传递:antispam
         **/
        data.put("scenes", Arrays.asList("antispam"));
        data.put("tasks", tasks);
        log.info("检测任务内容:{}", JSON.toJSONString(data, true));
        textScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
        // 请务必设置超时时间
        textScanRequest.setConnectTimeout(3000);
        textScanRequest.setReadTimeout(6000);

//        返回结果内容
        Map<String, String> resultMap = new HashMap<>();
        try {
            HttpResponse httpResponse = client.doAction(textScanRequest);
            if (!httpResponse.isSuccess()) {
                new RuntimeException("阿里云文本内容检查出现异常!");
            }
            JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
            log.info("检测结果内容:{}", JSON.toJSONString(scrResponse, true));
            if (200 != scrResponse.getInteger("code")) {
                new RuntimeException("阿里云文本内容检查出现异常!");
            }
            JSONArray taskResults = scrResponse.getJSONArray("data");
            for (Object taskResult : taskResults) {
                if (200 != ((JSONObject) taskResult).getInteger("code")) {
                    new RuntimeException("阿里云文本内容检查出现异常!");
                }
                JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                for (Object sceneResult : sceneResults) {
                    String scene = ((JSONObject) sceneResult).getString("scene");
                    String label = ((JSONObject) sceneResult).getString("label");
                    String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                    log.info("最终内容检测结果,suggestion = {},label={}", suggestion, label);
//                    设置默认错误返回内容
                    resultMap.put("suggestion", suggestion);
                    if (suggestion.equals("review")) {
                        resultMap.put("reson", "文章内容中有不确定词汇");
                        log.info("返回结果,resultMap={}", resultMap);
                        return resultMap;
                    } else if (suggestion.equals("block")) {
                        String reson = "文章内容中有敏感词汇";
                        if (label.equals("spam")) {
                            reson = "文章内容中含垃圾信息";
                        } else if (label.equals("ad")) {
                            reson = "文章内容中含有广告";
                        } else if (label.equals("politics")) {
                            reson = "文章内容中含有涉政";
                        } else if (label.equals("terrorism")) {
                            reson = "文章内容中含有暴恐";
                        } else if (label.equals("abuse")) {
                            reson = "文章内容中含有辱骂";
                        } else if (label.equals("porn")) {
                            reson = "文章内容中含有色情";
                        } else if (label.equals("flood")) {
                            reson = "文章内容灌水";
                        } else if (label.equals("contraband")) {
                            reson = "文章内容违禁";
                        } else if (label.equals("meaningless")) {
                            reson = "文章内容无意义";
                        }
                        resultMap.put("reson", reson);
                        log.info("返回结果,resultMap={}", resultMap);
                        return resultMap;
                    }

                }
            }
            resultMap.put("suggestion", "pass");
            resultMap.put("reson", "检测通过");

        } catch (Exception e) {
            log.error("阿里云文本内容检查出错!");
            e.printStackTrace();
            new RuntimeException("阿里云文本内容检查出错!");
        }
        log.info("返回结果,resultMap={}", resultMap);
        return resultMap;
    }

    /**
     * 阿里云图片内容安全
     */
    public Map imageScan(List<String> imageList) throws Exception {
        IClientProfile profile = DefaultProfile
                .getProfile("cn-shanghai", greenProperties.getAccessKeyID(), greenProperties.getAccessKeySecret());
        ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
        // 指定api返回格式
        imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
        // 指定请求方法
        imageSyncScanRequest.setMethod(MethodType.POST);
        imageSyncScanRequest.setEncoding("utf-8");
        //支持http和https
        imageSyncScanRequest.setProtocol(ProtocolType.HTTP);
        JSONObject httpBody = new JSONObject();
        /**
         * 设置要检测的场景, 计费是按照该处传递的场景进行
         * 一次请求中可以同时检测多张图片,每张图片可以同时检测多个风险场景,计费按照场景计算
         * 例如:检测2张图片,场景传递porn、terrorism,计费会按照2张图片鉴黄,2张图片暴恐检测计算
         * porn: porn表示色情场景检测
         */

        httpBody.put("scenes", Arrays.asList(greenProperties.getScenes().split(",")));

        /**
         * 如果您要检测的文件存于本地服务器上,可以通过下述代码片生成url
         * 再将返回的url作为图片地址传递到服务端进行检测
         */
        /**
         * 设置待检测图片, 一张图片一个task
         * 多张图片同时检测时,处理的时间由最后一个处理完的图片决定
         * 通常情况下批量检测的平均rt比单张检测的要长, 一次批量提交的图片数越多,rt被拉长的概率越高
         * 这里以单张图片检测作为示例, 如果是批量图片检测,请自行构建多个task
         */
        List list = new ArrayList();
        for (String imageUrl : imageList) {
            JSONObject task = new JSONObject();
            task.put("dataId", UUID.randomUUID().toString());
            // 设置图片链接。
            task.put("url", imageUrl);
            task.put("time", new Date());
            list.add(task);
        }

        httpBody.put("tasks",list);

        imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
                "UTF-8", FormatType.JSON);
        /**
         * 请设置超时时间, 服务端全链路处理超时时间为10秒,请做相应设置
         * 如果您设置的ReadTimeout小于服务端处理的时间,程序中会获得一个read timeout异常
         */
        imageSyncScanRequest.setConnectTimeout(3000);
        imageSyncScanRequest.setReadTimeout(10000);
        HttpResponse httpResponse = null;
        try {
            httpResponse = client.doAction(imageSyncScanRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map<String, String> resultMap = new HashMap<>();

        //服务端接收到请求,并完成处理返回的结果
        if (httpResponse != null && httpResponse.isSuccess()) {
            JSONObject scrResponse = JSON.parseObject(org.apache.commons.codec.binary.StringUtils.newStringUtf8(httpResponse.getHttpContent()));
            System.out.println(JSON.toJSONString(scrResponse, true));
            int requestCode = scrResponse.getIntValue("code");
            //每一张图片的检测结果
            JSONArray taskResults = scrResponse.getJSONArray("data");
            if (200 == requestCode) {
                for (Object taskResult : taskResults) {
                    //单张图片的处理结果
                    int taskCode = ((JSONObject) taskResult).getIntValue("code");
                    //图片要检测的场景的处理结果, 如果是多个场景,则会有每个场景的结果
                    JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                    if (200 == taskCode) {
                        for (Object sceneResult : sceneResults) {
                            String scene = ((JSONObject) sceneResult).getString("scene");
                            String label = ((JSONObject) sceneResult).getString("label");
                            String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                            //根据scene和suggetion做相关处理
                            //do something
                            System.out.println("scene = [" + scene + "]");
                            System.out.println("suggestion = [" + suggestion + "]");
                            System.out.println("suggestion = [" + label + "]");
                            if (!suggestion.equals("pass")) {
                                resultMap.put("suggestion", suggestion);
                                resultMap.put("label", label);
                                return resultMap;
                            }
                        }

                    } else {
                        //单张图片处理失败, 原因视具体的情况详细分析
                        log.error("task process fail. task response:" + JSON.toJSONString(taskResult));
                        return null;
                    }
                }
                resultMap.put("suggestion", "pass");
                return resultMap;
            } else {
                /**
                 * 表明请求整体处理失败,原因视具体的情况详细分析
                 */
                log.error("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
                return null;
            }
        }
        return null;
    }
}
TanhuaAutoConfiguration
@Bean
@ConditionalOnProperty(prefix = "tanhua.green",value = "enable", havingValue = "true")
public AliyunGreenTemplate aliyunGreenTemplate(GreenProperties properties) {
    return new AliyunGreenTemplate(properties);
}
配置文件
tanhua:
  green:
    enable: true
    accessKeyID: LTAI4GKgob9vZ53k2SZdyAC7
    accessKeySecret: LHLBvXmILRoyw0niRSBuXBZewQ30la
    scenes: porn,terrorism #色情,暴力
单元测试
    @Autowired
    private AliyunGreenTemplate template;

    @Test
    public void test() throws Exception {
//        Long data = analysisMapper.sumAnalysisData("num_registered", "2020-09-14", "2020-09-18");
//        System.out.println(data);
//        Map<String, String> map = template.greenTextScan("本校小额贷款,安全、快捷、方便、无抵押,随机随贷,当天放款,上门服务");
//        map.forEach((k,v)-> System.out.println(k +"--" + v));
        List<String> list = new ArrayList<>();
        list.add("http://images.china.cn/site1000/2018-03/17/dfd4002e-f965-4e7c-9e04-6b72c601d952.jpg");
        Map<String, String> map = template.imageScan(list);
        System.out.println("------------");
        map.forEach((k,v)-> System.out.println(k +"--" + v));
    }

3.2 动态审核

3.2.1 执行流程

为了解决程序间耦合关系,这里采用RabbitMQ + 阿里云完成内容审核

  • 用户发布动态,保存到数据库

  • 发送RabbitMQ消息

  • 管理后台监听消息,对内容(文本、图片审核)

  • 更新动态的状态
    在这里插入图片描述

3.2.2 发布消息
    public void publishMovement(Movement movement, MultipartFile[] imageContent) throws IOException {
        //1、判断发布动态的内容是否存在
        if(StringUtils.isEmpty(movement.getTextContent())) {
            throw  new BusinessException(ErrorResult.contentError());
        }
        //2、获取当前登录的用户id
        Long userId = UserHolder.getUserId();
        //3、将文件内容上传到阿里云OSS,获取请求地址
        List<String> medias = new ArrayList<>();
        for (MultipartFile multipartFile : imageContent) {
            String upload = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
            medias.add(upload);
        }
        //4、将数据封装到Movement对象
        movement.setUserId(userId);
        movement.setMedias(medias);
        //5、调用API完成发布动态
        String movementId = movementApi.publish(movement);
        try {
            amqpTemplate.convertSendAndReceive("tanhua.audit.exchange","audit.movement",movementId);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
3.2.3 监听器
@Component
public class MovementListener {

    @DubboReference
    private MovementApi movementApi;

    @Autowired
    private AliyunGreenTemplate aliyunGreenTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(
                    value = "tanhua.audit.queue",
                    durable = "true"
            ),
            exchange = @Exchange(
                    value = "tanhua.audit.exchange",
                    type = ExchangeTypes.TOPIC),
            key = {"audit.movement"})
    )
    public void listenCreate(String movementId) throws Exception {
        try {
            //1、根据动态id查询动态
            Movement movement = movementApi.findById(movementId);
            //对于RocketMQ消息有可能出现重复,解决方法判断 (幂等性)
            Integer state = 0;
            if(movement != null && movement.getState() == 0) {
                Map<String, String> textScan = aliyunGreenTemplate.greenTextScan(movement.getTextContent());
                Map<String, String> imageScan = aliyunGreenTemplate.imageScan(movement.getMedias());
                if(textScan != null && imageScan != null) {
                    String textSuggestion = textScan.get("suggestion");
                    String imageSuggestion = imageScan.get("suggestion");
                    if ("block".equals(textSuggestion) || "block".equals(textSuggestion)){
                        state = 2;
                    }else if("pass".equals(textSuggestion) || "pass".equals(textSuggestion)) {
                        state = 1;
                    }
                }
            }
            movementApi.update(movementId,state);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
3.2.4 movementApi
@Override
public void update(String movementId, Integer state) {
    Query query = Query.query(Criteria.where("id").in(new ObjectId(movementId)));
    Update update = Update.update("state", state);
    mongoTemplate.updateFirst(query,update,Movement.class);
}
AUTOSAR CP R18-10 架构总览与导航 AUTOSAR CP R18-10 架构总览 本文档系统整理了AUTOSAR CP R18-10版本的199篇技术规范,涵盖7大架构层级: 应用层(15篇):包含车身舒适、底盘控制、HMI、安全系统、动力系统等AI应用 RTE(1篇):虚拟功能总线规范 服务层(159篇):细分为系统服务(OS/ECU管理/加密)、存储服务、通信服务(CAN/LIN/Ethernet) ECU抽象层(20篇):I/O与通信硬件抽象 MCAL(41篇):微控制器驱动层 复杂驱动(14篇):CDD设计与SPAL支撑 规范模板(2 阅读详情

相关推荐

使用 ArcGIS Pro 和 Google Earth Engine 可视化地表温度

在这项研究中,利用 Landsat 热数据通过各种方法检查了 2013 年和 2023 年恰纳卡莱省的地表温度变化。使用了 NDVI、大气层顶部、亮度温度、植被比例和地表温度等公式。研究结果表明,从热图像中获得的数据,特别是地表温度(LST),是土地解释的重要资源。恰纳卡莱 — 土耳其(土耳其)使用 ArcGIS 程序和 Google Earth Engine 对不同季节的卫星图像进行分析。

gis收藏家的博客 2008

【探花交友DAY 10】网关和后台系统

Spring Gateway网关和探花交友后台管理系统的搭建

lyx7762的博客 1471

S4HANA Rebate Management(条件合同) -Single Step

S4HANA 条件合同管理(Condition Contract Management), 包括如何创建条件合同,场景应用

m0_50200150的博客 2309

【探花交友DAY 11】定时统计任务和自动内容审核

利用Spring Task实现定时统计信息,利用阿里云的内容识别实现对发布内容的合法性进行审核

lyx7762的博客 1359

STM32 SAES硬件加密协处理器全模式工程实践指南

AES(高级加密标准)是嵌入式系统中最基础且关键的对称密码算法,其硬件加速实现直接影响安全、性能与功耗平衡。Secure AES Coprocessor(SAES)作为STMicroelectronics在STM32U5等高安全MCU中集成的专用密码协处理器,不仅支持标准ECB/CBC/CTR模式,更原生兼容GCM和CCM等认证加密模式,具备抗侧信道、密钥保护与DMA卸载能力。理解其寄存器状态机(CHMOD/MODE/CPHASE)、NPBLB数据对齐机制及GCM四阶段编程范式,是规避Tag校验失败、IV错

weixin_42311427的博客 77

地震勘探中的频谱分析:从基础到应用

本文深入探讨了地震勘探中的频谱分析技术,从基础原理到实际应用。通过傅里叶变换等工具,频谱分析能有效识别不同地震波的频率特征,指导数据采集和处理。文章结合油田勘探案例,展示了如何利用振幅谱和相位谱提升信噪比,并介绍了智能滤波等前沿技术在地震数据处理中的应用。

weixin_42557830的博客 410

RabbitMQ —— 理解及应用场景

RabbitMQ —— 理解及应用场景

小蜜蜂vs码农 3915

手把手教你用西门子博图V18配置阿特拉斯PF6000拧紧枪PN通讯(附完整GSD文件与ToolsTalk配置文件)

本文详细介绍了如何使用西门子博图V18配置阿特拉斯PF6000拧紧枪的PN通讯,包括硬件连接、网络参数规划、ToolsTalk软件配置及博图工程设置。通过完整的GSD文件和配置文件,帮助工程师快速实现高精度拧紧设备与PLC的高效通讯,适用于汽车装配和电子制造等工业自动化场景。

weixin_42662293的博客 608

探花交友项目经验

业务说明:用户通过手机验证码进行登录,如果是第一次登录则需要完善个人信息,在上传图片时,需要对上传的图片做人像的校验,防止用户上传非人像的图片作为头像。流程完成后,则登录成功。项目基于前后端分离的架构进行开发,前后端分离架构总体上包括前端和服务端,通常是多人协作开发前后端分离开发基于HTTP+JSON交互通过接口文档(API文档)定义规范前后端按照文档定义请求及响应数据YAPI已经在linux虚拟机中准备好了/123456。

qq_57216731的博客 1万+

H3C交换机Console口连接全攻略:从接线到PuTTY配置(附常见问题排查)

本文详细介绍了H3C交换机Console口的连接与配置方法,包括硬件线缆选择、驱动安装、PuTTY参数设置及常见问题排查。特别针对Console转USB线缆的兼容性和驱动安装难点提供实用建议,帮助网络工程师快速掌握串联调试技巧,解决连接中的黑屏、乱码等典型问题。

weixin_42549451的博客 679

SAP公司间外协业务流程以及配置说明

SAP公司间外协业务流程以及配置说明

竹大的博客 7173

【探花交友DAY 12 完结】推荐系统

推荐系统与探花交友系统结合,实现动态,小视频和好友的推荐

lyx7762的博客 2075

rk3576 适配以太网(百兆)

百兆以太网,也常被称为快速以太网,是一种在1990年代中期推出的计算机网络技术标准。它相当于把当时主流的10兆以太网速度提升了10倍,最高能提供 100 Mbps 的传输速率,让文件共享、视频传输等网络应用变得流畅许多。它在数据链路层面完全保留了传统以太网的帧格式和MAC机制,这意味着现有的网络软件可以无缝对接,用户从10兆网络升级到百兆网络时,通常只需要更换网卡和集线器/交换机即可,非常方便。 在rk3576平台上,原生以太网接口支持百兆、千兆,还有pcie转换的2.5G。

weixin_35723192的博客 208

探花交友_第11章_数据统计与内容审核(新版)

1、用户冻结解冻 1.1 用户冻结 1.2 用户解冻 1.3 查询数据列表 1.4 探花系统修改 2、数据统计 2.1 数据采集 2.2 定时任务 3、内容审核 3.1 阿里云内容审核 3.2 动态审核

无 750

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

SpringBoot交友APP项目实战(详细介绍+案例源码) - 11.后台管理(完结啦)

搭建一个Java框架的移动端交友APP,涵盖登录、注册、动态、即时通讯、视频(算法推荐)、个人中心等功能; 技术选型: Spring Boot + SpringMVC + Mybatis + MybatisPlus + Dubbo,即时通讯选用环信即时通讯

yuan 5550

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

Java进行数据统计分析

常见的数据统计分析有:求和、平均数、中位数、众数、方差、均方差、极差、最大值、最小值等。本文从数理统计基础出发,简单总结了java中求以上统计分析量的算法,如下: //1.求和 public static double getSum(double[] arr){ double sum = 0; for(int i =0;i < arr.length;i++){ sum += arr[i]; } return sum; } //2.求平均数 publi...

qq_40820859的博客 7230

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

Java 项目实战: 交友项目 - 用户管理:查看用户详情

运营在用户列表点击「查看」,通过 GET /manage/users/{userId} 接口获取用户详情。接口基于 Dubbo 调用 UserInfoApi.findById 查询 UserInfo,返回包含昵称、头像、年龄、城市等字段的聚合数据。前端分三步渲染:先加载资料区(本章实现),再并发请求动态与视频记录列表。后端采用单点查询,由前端拼装聚合数据;未来可优化为并行聚合(CompletableFuture)提升性能。接口需处理用户不存在、越权等边界场景,返回值为 UserInfo 实体而非 VO,确保

Wang的专栏 366

Java 项目实战:交友项目视频功能——关注与取消关注的需求分析与代码实现

本文详解交友项目中视频关注功能的需求分析与实现。聚焦“关注”作为单向订阅关系,采用Redis Set存储关注者列表(key: FOCUS_USER_KEY_+userId),支持高效判存(SISMEMBER)、幂等增删(SADD/SREM)。结合生产双写方案:MongoDB持久化focus_user表,Redis缓存加速查询。接口设计为POST路径参数uid,操作人由token解析,确保安全。视频列表返回时回填hasFocus字段,实现“关注/取消关注”按钮两态切换。强调关注非好友,无需双向同步,避免误解。

Wang的专栏 928

Java 项目实战:交友项目 - 项目架构:网关的概述

本文系统阐述多服务架构下接入层的三大痛点:多后端地址、鉴权重复与跨域分散,并提出以网关为核心解决方案。网关作为统一入口,具备路由与过滤器两大能力,实现统一入口、鉴权、跨域/限流/日志等职责。其位于应用层最前端,工程上通过Spring Cloud Gateway构建,依赖Nacos实现服务发现与配置管理,路由规则由配置驱动,核心优势在于横切逻辑集中化,显著降低维护成本。

Wang的专栏 364

Java 项目实战:交友项目 - 管理员登录:根据用户名密码登录获取 token

本文实现后台登录闭环:前端提交用户名、密码、验证码及uuid,后端通过Redis校验图片验证码(用后即删),MD5比对密码,签发JWT token。核心链路由AdminService完成,涉及SystemController、AdminService、AdminMapper、JwtUtils等模块,登录后通过TokenInterceptor与AdminHolder实现鉴权。接口路径为POST /system/users/login,返回{"token": "..."},完整流程涵盖验证码验证、密码校验、JW

Wang的专栏 235

Java 项目实战: 交友项目 - 用 Nacos 配置中心托管各服务配置

交友项目接入Nacos配置中心,解决配置分散、需重启服务、敏感信息泄露三大痛点。通过在各模块添加spring-cloud-starter-alibaba-nacos-config依赖,配置bootstrap.yml实现优先加载,按{service-name}-{profile}.{format}规则(如mf-gateway-dev.yml)动态拉取配置。改造后,网关路由与白名单等配置可实时生效,无需重启。最终实现统一管理、环境隔离与安全可控的配置体系。

Wang的专栏 262

Java 项目实战: 交友项目 - 用户管理:查看动态列表

该接口用于后台管理动态,支持用户动态查看与审核共用。因动态需跨MongoDB(动态数据)与MySQL(用户资料)查询,并返回含用户信息的MovementsVo,故链路复杂:通过Dubbo调用MovementApi查动态,再批量获取用户资料并转换为VO。接口GET /manage/messages支持uid与state可选过滤,实现动态拼接条件查询,满足多场景需求。

Wang的专栏 657

Java 项目实战: 交友项目 - 完善项目架构:总结

本文总结「完善项目架构」专题,构建统一接入层:通过 Spring Cloud Gateway 实现路由、鉴权、CORS 集中管理,结合 Nacos 配置中心实现动态配置与服务发现。形成“客户端 → 网关 → 应用服务 → Dubbo 域服务”四层架构,解决鉴权分散、地址硬编码、跨域重复配置等问题。提炼三类可复用模式:网关标准配置、鉴权上移边界、配置中心使用规范;汇总六大高频坑点,强调配置优先级、响应式写法、动态刷新等关键细节。最终实现接入成本降低、安全增强、运维便捷的演进收益。

Wang的专栏 203

Java 项目实战: 交友项目 - 完善项目架构:架构问题分析

当前交友项目采用“Web层+Dubbo服务层”架构,虽服务层已实现集群高可用,但接入层仍为多独立Web应用,导致前端地址分散、鉴权重复、跨域配置不一、流量治理缺失。核心问题在于缺乏统一入口,亟需引入API网关,实现请求聚合、统一鉴权、集中限流与日志监控,提升系统可维护性与安全性。

Wang的专栏 869

Java 项目实战:交友项目 - 小视频方案总结与自检

本文梳理小视频模块全链路设计:访客记录存Mongo、视频文件分发至FastDFS与OSS、视频列表采用“Redis推荐+数据库兜底”策略,并通过SpringCache实现30秒缓存闭环。提炼出五项可复用套路——三存储协同、声明式缓存闭环、增量游标自维护、推荐优先兜底、同构多维扩展,揭示文件存储分流的决策逻辑。回顾12个关键坑,如Long比较、坐标顺序错误、异步失效等,强调代码严谨性。附自检清单与改造练习,助力快速落地类似功能。

Wang的专栏 548

Java 项目实战: 交友项目 - 通用缓存SpringCache:配置视频列表缓存功能

在交友项目中,为视频列表接口 queryVideoList 添加 @Cacheable 实现读缓存,按用户+页码键值缓存结果;发布视频时通过 @CacheEvict(allEntries=true) 清空 videos 命名空间缓存,确保数据一致性。配合 RedisCacheConfig 设置 30 秒 TTL,形成“读缓存、写失效”的闭环。启动类启用 @EnableCaching,结合 redis-cli 验证缓存命中与失效流程,有效降低高频查询的链路开销,提升响应性能。

Wang的专栏 630
上一篇: 探花交友07-搜附近
下一篇: 探花交友11-实现推荐系统
InLoadwetrust
博客等级 码龄6年 11粉丝 84原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

InLoadwetrust

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值