Commit bcfbd8dc authored by 张辰's avatar 张辰

Merge branch 'dev' into 'master'

Dev

See merge request !3
parents 6cb84b00 08c07618
......@@ -20,4 +20,7 @@ public final class CommunityConstant {
public static final String OSS_PREFIX_FOLDER ="community/";
//图片压缩比例:50%
public static final String OSS_RESIZE_RATIO = "?x-oss-process=image/resize,p_50";
}
......@@ -22,8 +22,6 @@ public class ThemeAnalysDO {
@ApiModelProperty(value = "作者id")
private String authorId;
@ApiModelProperty(value = "被转发的主题")
private String formerThemeId;
@ApiModelProperty(value = "所属的话题")
private String topicId;
......@@ -44,18 +42,12 @@ public class ThemeAnalysDO {
private Integer viewCount;
@ApiModelProperty(value = "距今时间")
private Long minuteTillNow;
private Long minutesTillNow;
@ApiModelProperty(value = "用户质量")
private Double userWeight = 0.0;
public Double getRank() {
// 质量=帖子质量+用户质量
double w = (double) (viewCount * 0.1 + forwardCount * 3 + commentCount * 2 + likeCount * 1 + collectCount * 3) + userWeight;
double i = 1;//初试权重
double t = Double.valueOf(minuteTillNow) / 60;
double g = 0.1;//时间系数
return (w + i) / Math.pow(t + 1, g);
}
private Double score=0.0;
}
......@@ -56,8 +56,6 @@ public class ThemeQo implements Serializable {
@ApiModelProperty(value = "当前用户是否关注该作者")
public boolean follow;
@ApiModelProperty(value = "认证机构")
private String authOrg;
......
......@@ -38,21 +38,7 @@ public class TopicRankQo {
@ApiModelProperty(value = "话题下的帖子权重")
private Double themeWeight;
private Integer hoursTillNow;
/**
* 热度计算算法
*
* @return
*/
public Double getRank() {
double g = 0.3;//时间系数
//顶置话题
if (isTop > 0) {
return Double.MAX_VALUE;
}
Double socre = ((disscussCount * 3 + viewCount) / Math.pow(hoursTillNow + 1, g)) + themeWeight;
return socre;
}
private Integer minutesTillNow;
private Double score;
}
......@@ -10,11 +10,11 @@ import lombok.Data;
public class QueryFollowReq {
@ApiModelProperty(value = "用户Id")
private String userId;
public String userId;
@ApiModelProperty(value = "查询类型,1:粉丝 2:关注")
private Integer queryType;
public Integer queryType;
@ApiModelProperty(value = "分页")
private Pageable page;
public Pageable page;
}
......@@ -22,6 +22,9 @@ public class ImagesDTO {
@ApiModelProperty("图片url")
private String remark;
@ApiModelProperty("压缩图片url")
private String resizeUrl;
@ApiModelProperty("图片宽度")
private Integer imgHeight;
......
......@@ -19,9 +19,8 @@ import java.io.Serializable;
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(description = "用户信息 首席投顾专用信息")
public class UserInfoNewChief implements Serializable {
public class UserInfoNewChief {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "用户id")
private String userId;
......@@ -57,4 +56,7 @@ public class UserInfoNewChief implements Serializable {
@ApiModelProperty(value = "头像url")
private String headImageUrl;
@ApiModelProperty(value = "首席投顾数量")
private Long chiefCount;
}
\ No newline at end of file
package com.tanpu.community.api.beans.vo.feign.fatools;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.Date;
......@@ -20,44 +22,11 @@ import java.util.Date;
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(description = "用户信息 机构")
public class UserInfoNewOrg implements Serializable {
private static final long serialVersionUID = 1L;
public class UserInfoNewOrg {
//↓↓↓↓ 机构 ↓↓↓↓
// @ApiModelProperty(value = "申请用户id")
// private String applyUserId;
// @ApiModelProperty(value = "机构id")
// private String userIdOrg;
// @ApiModelProperty(value = "公司名称")
// private String companyName;
// @ApiModelProperty(value = "公司全称")
// private String companyFullName;
// @ApiModelProperty(value = "营业执照账号")
// private String businessLicenseNumber;
// @ApiModelProperty(value = "营业执照 图片url")
// private String businessLicenseImageUrl;
// @ApiModelProperty(value = "机构用户身份公函 url")
// private String identityLetterUrl;
// @ApiModelProperty(value = "机构认证信息登记表 url")
// private String orgAuthInfoFormUrl;
// @ApiModelProperty(value = "运营人员 职位")
// private String position;
// @ApiModelProperty(value = "审核状态 1初始提交 2审核不通过 3审核通过")
// private Integer auditStatus;
// @ApiModelProperty(value = "认证名称")
// private String certName;
// @ApiModelProperty(value = "是否匹配现有基金公司 0不匹配 1匹配")
// private Integer isExistOrg;
// @ApiModelProperty(value = "所属基金公司id")
// private String belongOrgId;
// @ApiModelProperty(value = "所属基金公司类型 0公募 1私募")
// private Integer belongOrgType;
@ApiModelProperty(value = "机构id")
private String corpId;
@ApiModelProperty(value = "公司简称")
private String corpShortName;
@ApiModelProperty(value = "公司全称")
private String corpName;
@ApiModelProperty(value = "营业执照账号")
......@@ -73,6 +42,8 @@ public class UserInfoNewOrg implements Serializable {
@ApiModelProperty(value = "审核状态 0待审核 1通过 2驳回")
private Integer auditStatus;
@ApiModelProperty(value = "审核时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date auditTime;
@ApiModelProperty(value = "运营人员姓名")
private String operatorName;
......
......@@ -2,8 +2,10 @@ package com.tanpu.community.api.beans.vo.feign.fatools;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @description: 机构人员信息
......@@ -12,6 +14,8 @@ import lombok.Data;
**/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(description = "用户信息 机构人员信息")
public class UserInfoOrg {
......
......@@ -37,8 +37,8 @@ public class UserInfoResp {
@ApiModelProperty("基金数")
private Integer fundNumber = 0;
@ApiModelProperty("成立时间")
private long founded;
@ApiModelProperty("成立时间 yyyy-MM-dd")
private String founded;
@ApiModelProperty("备案编号")
private String recordNumber = "-";
@ApiModelProperty("团队成员")
......
......@@ -2,32 +2,12 @@ package com.tanpu.community.api.constants;
public class RedisKeyConstant {
//话题页浏览量
public static final String TOPIC_PAGE_VIEW_COUNT_ ="TOPIC_PAGE_VIEW_COUNT_";
//话题总浏览量=总浏览量+带这个话题的帖子量
public static final String TOPIC_TOTAL_VIEW_COUNT_="TOPIC_TOTAL_VIEW_COUNT_";
//点赞量
public static final String TOPIC_LIKE_COUNT_="TOPIC_LIKE_COUNT_";
public static final String THEME_LIKE_COUNT ="THEME_LIKE_COUNT_";
//收藏量
public static final String TOPIC_BOOK_COUNT_="TOPIC_BOOK_COUNT_";
//用户数
public static final String TOPIC_USER_COUNT_="TOPIC_USER_COUNT_";
public static final String THEME_COMMENT_COUNT ="THEME_COMMENT_COUNT_";
//讨论量=发布主题贴数+回复总数
public static final String TOPIC_DISCUSS_COUNT_="TOPIC_DISCUSS_COUNT_";
//发帖数
public static final String TOPIC_THEME_COUNT_="TOPIC_THEME_COUNT_";
//回帖数
public static final String TOPIC_COMMENT_COUNT_="TOPIC_COMMENT_COUNT_";
//总用户数=访问话题页+发帖+回帖(去重)
public static final String TOPIC_TOTAL_USER_COUNT_ ="TOPIC_TOTAL_USER_COUNT_";
//访问话题人数
public static final String TOPIC_USER_VIEW_COUNT_="TOPIC_USER_VIEW_COUNT_";
//发帖人数
public static final String TOPIC_POST_USER_COUNT_ ="TOPIC_POST_USER_COUNT_";
//回帖人数
public static final String TOPIC_COMMENT_USER_COUNT_ ="TOPIC_COMMENT_USER_COUNT_";
// 出现在用户的搜索列表中的主题id
public static final String THEME_APPEAR_IN_SEARCH_LIST = "THEME_APPEAR_IN_SEARCH_LIST_";
public static final String THEME_FORWARD_COUNT ="THEME_FORWARD_COUNT_";
// feign 查询用户信息
public static final String CACHE_FEIGN_USER_INFO = "CACHE_FEIGN_USER_INFO_";
......@@ -38,12 +18,9 @@ public class RedisKeyConstant {
// 主题本身
public static final String CACHE_THEME_ID = "CACHE_THEME_ID_";
// 转发主题本身
public static final String CACHE_FORMER_THEME_ID = "CACHE_FORMER_THEME_ID_";
public static final String CACHE_FORWARD_THEME_ID = "CACHE_FORWARD_THEME_ID_";
// 关注的人,上次浏览的最新主题last id
public static final String CACHE_IDOL_THEME_LAST_ID = "CACHE_IDOL_THEME_LAST_ID_";
public static final String THEME_VIEW_COUNT_="THEME_VIEW_COUNT_";
public static final String THEME_LIKE_COUNT_="THEME_LIKE_COUNT_";
public static final String THEME_BOOK_COUNT_="THEME_BOOK_COUNT_";
}
......@@ -9,7 +9,7 @@ public enum FileTypeEnum {
IMAGE(1,"图片类型"),QUERY_IDOLS(2,"查询关注");
public static final HashSet<String> imageTypeSet = SetUtils.hashSet("jpg", "jpeg", "png");
public static final HashSet<String> ossTypeSet = SetUtils.hashSet("jpg", "jpeg", "png", "txt");
private Integer code;
private String type;
......
package com.tanpu.community.api.enums;
import org.apache.commons.collections4.SetUtils;
import java.util.HashSet;
public enum ThemeRecordTypeEnum {
PUBLISH_LIST(1,"发布列表"),
COMMENT_LIST(2,"评论列表"),
LIKE_LIST(3,"点赞"),
COLLECT_LIST(4,"收藏");
public static final HashSet<String> imageTypeSet = SetUtils.hashSet("jpg", "jpeg", "png");
private Integer code;
private String type;
ThemeRecordTypeEnum(Integer code, String type) {
this.code = code;
this.type = type;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
......@@ -10,6 +10,7 @@ import com.tanpu.community.api.beans.resp.FileUploadResp;
import com.tanpu.community.api.enums.OssDirEnum;
import com.tanpu.community.cache.RedisCache;
import com.tanpu.community.manager.FileManager;
import com.tanpu.community.service.RankLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.caffeine.CaffeineCacheManager;
......@@ -28,6 +29,9 @@ public class FileController {
@Autowired
private FileManager fileManager;
@Autowired
private RankLogService rankLogService;
@Resource
private UserHolder userHolder;
......@@ -47,28 +51,16 @@ public class FileController {
return CommonResp.success(fileManager.uploadFile(file, OssDirEnum.Theme_Pic, userId));
}
@GetMapping("/test")
public String test() {
// redisCache.put("11111", JsonUtil.toJson(list), 60);
//
// String v = redisCache.get("11111");
// System.out.println(v);
// System.out.println(JsonUtil.toJson(JsonUtil.toBean(v, new TypeReference<List<String>>() {
// })));
@GetMapping("/clearRankLog")
public String clearRankLog() {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
rankLogService.clearRankLog();
}
});
// localCache.getCache("local").put("999", "6666666");
// System.out.println((String) localCache.getCache("local").get("999").get());
//
//
// for (int i = 0; i < 30; i++) {
// System.out.println(fileManager.getId("" + i / 2));
// }
//
// for (int i = 30; i > 0; i--) {
// System.out.println(fileManager.getId("" + i / 2));
// }
return "";
t.start();
return "success";
}
}
......@@ -78,6 +78,7 @@ public class HomePageController {
@PostMapping(value = "/addIdol")
@ApiOperation("关注/取消关注他人")
@ResponseBody
@AuthLogin
public CommonResp addIdol(@RequestBody FollowRelReq req) {
String userId = userHolder.getUserId();
homePageManager.addFollowRel(req, userId);
......
......@@ -52,7 +52,7 @@ public class ThemeController {
@ResponseBody
public CommonResp<ThemeQo> getDetail(@RequestParam(value = "themeId") String themeId) {
String userId = userHolder.getUserId();
return CommonResp.success(themeManager.getThemeDetail(themeId, userId));
return themeManager.getThemeDetail(themeId, userId);
}
@AuthLogin
......
......@@ -31,7 +31,7 @@ public class TopicController {
@PostMapping(value = "/list")
@ApiOperation("APP全部话题页面,可搜索")
@ResponseBody
public CommonResp<Page<TopicRankQo>> getTopicBriefInfoList(@RequestBody TopicSearchReq req){
public CommonResp<Page<TopicRankQo>> getTopicList(@RequestBody TopicSearchReq req){
return CommonResp.success(topicManager.getAllTopicBriefInfo(req));
}
......@@ -39,15 +39,15 @@ public class TopicController {
@GetMapping(value = "/detailPage")
@ApiOperation("话题详情页顶部")
@ResponseBody
public CommonResp<TopicRankQo> gethotThemes(@RequestParam String topicId){
return CommonResp.success(topicManager.getDetail(topicId));
public CommonResp<TopicRankQo> getDetail(@RequestParam String topicId){
return topicManager.getDetail(topicId);
}
@GetMapping(value = "/titleList")
@ApiOperation("首页顶部话题标题列")
@ResponseBody
public CommonResp<List<TopicRankQo>> getTitleList(){
public CommonResp<List<TopicRankQo>> getTop4Topic(){
return CommonResp.success(topicManager.getTop4TopicTitles());
}
......
package com.tanpu.community.dao;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.tanpu.community.api.CommunityConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
/**
* created by xd on 2021/6/3
*/
@Configuration
@Slf4j
@MapperScan(basePackages = CommunityConstant.PACKAGE_BASE + ".dao.mapper.user", sqlSessionTemplateRef = "userSqlSessionTemplate")
public class UserDataSourceConfig {
@ConfigurationProperties(prefix = "spring.datasource.user")
@Bean(name = "userDataSource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "userSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("userDataSource") DataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(
"classpath*:mapper/user/*.xml"));
return bean.getObject();
}
@Bean(name = "userTransactionManager")
public DataSourceTransactionManager userTransactionManager(@Qualifier("userDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "userSqlSessionTemplate")
public SqlSessionTemplate userSqlSessionTemplate(@Qualifier("userSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
package com.tanpu.community.dao;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.tanpu.community.api.CommunityConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
/**
* created by xd on 2021/6/3
*/
@Configuration
@Slf4j
@MapperScan(basePackages = CommunityConstant.PACKAGE_BASE + ".dao.mapper.zhibo", sqlSessionTemplateRef = "zhiboSqlSessionTemplate")
public class ZhiboDataSourceConfig {
@ConfigurationProperties(prefix = "spring.datasource.zhibo")
@Bean(name = "zhiboDataSource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "zhiboSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("zhiboDataSource") DataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(
"classpath*:mapper/zhibo/*.xml"));
return bean.getObject();
}
@Bean(name = "zhiboTransactionManager")
public DataSourceTransactionManager zhiboTransactionManager(@Qualifier("zhiboDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "zhiboSqlSessionTemplate")
public SqlSessionTemplate zhiboSqlSessionTemplate(@Qualifier("zhiboSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
......@@ -54,6 +54,8 @@ public class RankLogEntity implements Serializable {
@ApiModelProperty(value = "排序时间")
private LocalDateTime rankTime;
private Long round;
private LocalDateTime createTime;
private LocalDateTime updateTime;
......@@ -125,6 +127,14 @@ public class RankLogEntity implements Serializable {
this.rankTime = rankTime;
}
public Long getRound() {
return round;
}
public void setRound(Long round) {
this.round = round;
}
public LocalDateTime getCreateTime() {
return createTime;
}
......
......@@ -2,6 +2,10 @@ package com.tanpu.community.dao.mapper.community;
import com.tanpu.community.dao.entity.community.RankLogEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* <p>
......@@ -13,4 +17,9 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
*/
public interface RankLogMapper extends BaseMapper<RankLogEntity> {
}
@Select("select max(round) from rank_log where type = #{type}")
Long selectMaxRound(@Param("type") Integer type);
@Select("select * from rank_log where type = #{type} order by id asc limit #{batchSize}")
List<RankLogEntity> selectByTypeLimit(@Param("type") Integer type, @Param("batchSize") Integer batchSize);
}
\ No newline at end of file
......@@ -21,8 +21,8 @@ import java.util.List;
* @since 2021-07-28
*/
public interface VisitLogMapper extends BaseMapper<VisitLogEntity> {
@Select("select * from visit_log where ident=#{ident} and ref_id=#{refId}")
VisitLogEntity selectByIdentAndRefId(@Param("ident") String ident, @Param("refId") String refId);
@Select("select * from visit_log where ident=#{ident} and ref_id=#{refId} and ref_type=#{refType}")
VisitLogEntity selectByIdentAndRefId(@Param("ident") String ident, @Param("refId") String refId, @Param("refType") String refType);
@Update("update visit_log set duration=duration+#{duration} where ident=#{ident}")
void updateDurByIdent(@Param("duration") Integer dur, @Param("ident") String ident);
......
package com.tanpu.community.dao.mapper.zhibo;
import com.tanpu.community.dao.entity.zhibo.ZhiboThemeEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 直播间信息表 Mapper 接口
* </p>
*
* @author xudong
* @since 2021-06-23
*/
public interface ZhiboThemeMapper extends BaseMapper<ZhiboThemeEntity> {
}
......@@ -52,6 +52,14 @@ public class CommentManager {
// 评论(对主题)
// 发表评论(对主题)
public void comment(CreateCommentReq req, String userId) {
if (StringUtils.isEmpty(req.getComment())) {
throw new IllegalArgumentException("评论内容不能为空");
}
if (req.getComment().length()>500){
throw new IllegalArgumentException("评论内容不能超过500字");
}
CommentEntity commentEntity = CommentEntity.builder()
.themeId(req.getThemeId())
.parentId(req.getParentId())
......
package com.tanpu.community.manager;
import com.tanpu.community.service.RankService;
import com.tanpu.community.service.RedisService;
import com.tanpu.community.service.VisitLogService;
import com.tanpu.community.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
......@@ -23,6 +21,12 @@ public class ConJobManager {
@Autowired
private RankService rankService;
@Autowired
private RankLogService rankLogService;
@Autowired
private RecommendService recommendService;
/**
* 定时统计 话题 访问数据,并刷到redis
*/
......@@ -36,9 +40,25 @@ public class ConJobManager {
/**
* 定时统计主题、话题排行
*/
@Scheduled(cron = "0 */2 * * * ?")
@Scheduled(cron = "*/30 * * * * ?")
public void themeRank() {
rankService.rankThemes();
rankService.rankTopics();
}
/**
* 定时统计主题、话题排行
*/
@Scheduled(cron = "*/5 * * * * ?")
public void getThemeNewest() {
recommendService.refreshNewestThemes();
}
/**
* 定时把rank_log的日志拿出来,清理数据库
*/
@Scheduled(cron = "0 0 0 ? * 1")
public void clearRankLog() {
rankLogService.clearRankLog();
}
}
......@@ -6,6 +6,7 @@ import com.tanpu.biz.common.enums.user.UserTypeEnum;
import com.tanpu.common.api.CommonResp;
import com.tanpu.common.constant.BizStatus;
import com.tanpu.common.exception.BizException;
import com.tanpu.common.util.DateUtils;
import com.tanpu.community.api.beans.qo.FollowQo;
import com.tanpu.community.api.beans.req.homepage.FollowRelReq;
import com.tanpu.community.api.beans.req.homepage.QueryFollowReq;
......@@ -58,7 +59,8 @@ public class HomePageManager {
//查询 个人中心 相关信息
public UserInfoResp queryUsersInfo(String userIdMyself, String userId) {
CommonResp<UserInfoResp> queryUsersListNew = feignClientForFatools.queryUsersListNew(StringUtils.isNotBlank(userId) ? userId : userIdMyself);
if (queryUsersListNew.isNotSuccess() || !ObjectUtils.anyNotNull(queryUsersListNew.getData())) throw new BizException("内部接口调用失败");
if (queryUsersListNew.isNotSuccess() || !ObjectUtils.anyNotNull(queryUsersListNew.getData()))
throw new BizException("内部接口调用失败");
UserInfoResp userInfoNew = queryUsersListNew.getData();
if (StringUtils.isNotBlank(userId) && !StringUtils.equals(userIdMyself, userId)) { //查询别人的个人主页
......@@ -92,6 +94,13 @@ public class HomePageManager {
userInfoNew.getUserInfoNewChief().setClientId(null);
}
}
// 查询首席投顾数量
CommonResp<Page<UserInfoNewChief>> pageCommonResp = feignClientForFatools.queryChiefFinancialAdviserList(1, 1);
if (pageCommonResp.isSuccess()) {
userInfoNew.getUserInfoNewChief().setChiefCount(pageCommonResp.getData().getTotalSize());
} else {
userInfoNew.getUserInfoNewChief().setChiefCount(0L);
}
} else if (UserTypeEnum.USER_ORG.getCode() == userInfoNew.getUserType()) {
......@@ -105,7 +114,7 @@ public class HomePageManager {
CommonResp<FundCompanySimpleVO> fundCompanyInfoSimple = feignForPublicFund.getFundCompanyInfoSimple(userInfoNew.getUserInfoNewOrg().getRelationFundCompanyId());
if (fundCompanyInfoSimple.isSuccess()) {
FundCompanySimpleVO data = fundCompanyInfoSimple.getData();
userInfoNew.setFounded(data.getEstablishDate());
userInfoNew.setFounded(data.getEstablishDate() > 0 ? DateUtils.formatYMD(new Date(data.getEstablishDate())) : null);
userInfoNew.setRecordNumber(data.getRegisterNumber());
}
}
......@@ -114,7 +123,7 @@ public class HomePageManager {
CommonResp<FundCompanySimpleVO> fundCompanyInfoSimple = feignForFund.getFundCompanyInfoSimple(userInfoNew.getUserInfoNewOrg().getRelationFundCompanyId());
if (fundCompanyInfoSimple.isSuccess()) {
FundCompanySimpleVO data = fundCompanyInfoSimple.getData();
userInfoNew.setFounded(data.getEstablishDate());
userInfoNew.setFounded(data.getEstablishDate() > 0 ? DateUtils.formatYMD(new Date(data.getEstablishDate())) : null);
userInfoNew.setRecordNumber(data.getRegisterNumber());
}
// 设置 基金数
......@@ -128,8 +137,8 @@ public class HomePageManager {
// 设置关注列表
List<String> collect = userInfoOrgs.stream().map(UserInfoOrg::getUserId).collect(Collectors.toList());
List<FollowRelEntity> followRelEntities = followRelMapper.selectList(new LambdaQueryWrapper<FollowRelEntity>()
.eq(FollowRelEntity::getIdolId, userId)
.in(FollowRelEntity::getFansId, collect)
.in(FollowRelEntity::getIdolId, collect)
.eq(FollowRelEntity::getFansId, userIdMyself)
.eq(FollowRelEntity::getDeleteTag, BizStatus.DeleteTag.tag_init));
Map<String, FollowRelEntity> collect1 = followRelEntities.stream().collect(Collectors.toMap(FollowRelEntity::getIdolId, Function.identity()));
userInfoOrgs.forEach(userInfoOrg -> {
......@@ -171,25 +180,34 @@ public class HomePageManager {
}
//获取用户关注、粉丝列表
/**
* 用户关注列表
*
* @param req 目标用户
* @param userId 当前用户
* @return
*/
public Page<FollowQo> queryFollow(QueryFollowReq req, String userId) {
//TODO 数据库分页
List<String> userIds = QueryFollowTypeEnum.QUERY_FANS.getCode().equals(req.getQueryType()) ?
followRelService.queryFansByIdolId(req.getUserId()) : followRelService.queryIdolsByFollowerId(req.getUserId());
//数据库分页
Integer pageSize = req.page.pageSize;
Integer pageNumber = req.page.pageNumber;
Page<String> userIdsPage = QueryFollowTypeEnum.QUERY_FANS.getCode().equals(req.getQueryType()) ?
followRelService.queryFansByIdolId(req.userId, pageNumber, pageSize)
: followRelService.queryIdolsByFansId(req.userId, pageNumber, pageSize);
List<FollowQo> followQos = new ArrayList<>();
if (!CollectionUtils.isEmpty(userIds)) {
List<UserInfoResp> userInfoNews = feignClientForFatools.queryUserListNew(userIds);
if (!CollectionUtils.isEmpty(userIdsPage.getContent())) {
List<UserInfoResp> userInfoNews = feignClientForFatools.queryUserListNew(userIdsPage.getContent());
List<FollowQo> collect = userInfoNews.stream().map(ConvertUtil::userInfoNew2FollowQo).collect(Collectors.toList());
followQos = judgeFollowed(collect, userId);
}
//分页
return PageUtils.page(req.getPage(), followQos);
return PageUtils.page(userIdsPage,followQos);
}
//判断返回列表中的用户是否被当前用户关注
public List<FollowQo> judgeFollowed(List<FollowQo> followQos, String followerId) {
Set<String> idolSet = new HashSet<>(followRelService.queryIdolsByFollowerId(followerId));
Set<String> idolSet = new HashSet<>(followRelService.queryIdolsByFansId(followerId));
return followQos.stream().map(o -> {
if (idolSet.contains(o.getUserId())) {
o.setFollowed(true);
......
package com.tanpu.community.manager;
import com.tanpu.common.auth.UserHolder;
import com.tanpu.common.api.CommonResp;
import com.tanpu.common.constant.ErrorCodeConstant;
import com.tanpu.community.api.beans.qo.TopicRankQo;
import com.tanpu.community.api.beans.req.page.Page;
import com.tanpu.community.api.beans.req.topic.TopicSearchReq;
import com.tanpu.community.dao.entity.community.TopicEntity;
import com.tanpu.community.service.RankService;
import com.tanpu.community.service.TopicService;
import com.tanpu.community.service.VisitLogService;
import com.tanpu.community.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import static com.tanpu.biz.common.enums.clue.PageEnum.COMM_VISIT_TOPIC_DETAIL;
@Service
public class TopicManager {
@Autowired
private VisitLogService visitLogService;
private TopicService topicService;
@Autowired
private RankService rankService;
@Resource
private UserHolder userHolder;
// 首页-话题标签
......@@ -43,11 +39,12 @@ public class TopicManager {
}
// 话题详情页
public TopicRankQo getDetail(String topicId) {
//TODO 临时埋点,接入新埋点后删除
visitLogService.addPageView(userHolder.getUserId(), topicId, COMM_VISIT_TOPIC_DETAIL);
return rankService.getTopicDetail(topicId);
public CommonResp<TopicRankQo> getDetail(String topicId) {
TopicEntity topicEntity = topicService.queryById(topicId);
if (topicEntity==null){
return CommonResp.error(ErrorCodeConstant.TOPIC_NOT_FOUND.getCode(), "抱歉!该话题已下线。");
}
return CommonResp.success(rankService.getTopicDetail(topicId));
}
......
......@@ -31,7 +31,7 @@ public class VisitSummaryManager {
@KafkaListener(topics = kafakTopic)
public void updateVisitSummary(String message) {
// {"durMillsInc":10000,"ident":"AD7B8CE8-2DA4-4FB4-907F-C551B926BA5C","localDate":"2021-08-02","pageId":"p13503","refId":"88737580570230824","visitorId":"275321532031467520"}
log.info("receive kafka msg: {}", message);
// log.info("receive kafka msg: {}", message);
KafkaDurationUptMsg msg = JSON.parseObject(message, KafkaDurationUptMsg.class);
// ident在每次进入新页面 & 回退 的时候都会随机生成一个,所以用ident做唯一key即可。
......
......@@ -7,6 +7,7 @@ import com.tanpu.biz.common.enums.user.UserLevelEnum;
import com.tanpu.common.api.CommonResp;
import com.tanpu.common.enums.fund.ProductTypeEnum;
import com.tanpu.common.util.JsonUtil;
import com.tanpu.community.api.CommunityConstant;
import com.tanpu.community.api.beans.qo.AttachmentDetailVo;
import com.tanpu.community.api.beans.qo.ThemeContentQo;
import com.tanpu.community.api.beans.qo.ThemeQo;
......@@ -258,10 +259,10 @@ public class BatchFeignCallService {
Set<String> ifaFundIds,
Set<String> notNetFundIds,
Map<String, FundInfoBaseResp> fundMap) {
Map<String, FundInfoBaseResp> tampFundMap = null;
Map<String, FundInfoBaseResp> privateFundMap = null;
Map<String, FundInfoBaseResp> publicFundMap = null;
Map<String, FundInfoBaseResp> ifaFundMap = null;
Map<String, FundInfoBaseResp> tampFundMap;
Map<String, FundInfoBaseResp> privateFundMap;
Map<String, FundInfoBaseResp> publicFundMap;
Map<String, FundInfoBaseResp> ifaFundMap;
Map<String, FundInfoBaseResp> notNetFundMap = null;
if (!CollectionUtils.isEmpty(tanpuFundIds)) {
// ProductListReq productListReq = ProductListReq.builder()
......@@ -276,7 +277,7 @@ public class BatchFeignCallService {
}).collect(Collectors.toList());
tampFundMap = fundInfoBaseRespList.stream().collect(Collectors.toMap(FundInfoBaseResp::getFundId, item -> item));
if (tampFundMap != null && tampFundMap.size() > 0) {
if (tampFundMap.size() > 0) {
fundMap.putAll(tampFundMap);
}
}
......@@ -291,7 +292,7 @@ public class BatchFeignCallService {
}).collect(Collectors.toList());
privateFundMap = fundInfoBaseRespList.stream().collect(Collectors.toMap(FundInfoBaseResp::getFundId, item -> item));
if (privateFundMap != null && privateFundMap.size() > 0) {
if (privateFundMap.size() > 0) {
fundMap.putAll(privateFundMap);
}
}
......@@ -307,7 +308,7 @@ public class BatchFeignCallService {
ifaFundMap = fundInfoBaseRespList.stream().collect(Collectors.toMap(FundInfoBaseResp::getFundId, item -> item));
if (ifaFundMap != null && ifaFundMap.size() > 0) {
if (ifaFundMap.size() > 0) {
fundMap.putAll(ifaFundMap);
}
}
......@@ -322,7 +323,7 @@ public class BatchFeignCallService {
}).collect(Collectors.toList());
publicFundMap = fundInfoBaseRespList.stream().collect(Collectors.toMap(FundInfoBaseResp::getFundId, item -> item));
if (publicFundMap != null && publicFundMap.size() > 0) {
if (publicFundMap.size() > 0) {
fundMap.putAll(publicFundMap);
}
}
......@@ -427,23 +428,26 @@ public class BatchFeignCallService {
//单图封装到imglist列表中
if (imgUrlMap.containsKey(themeContent.getValue())) {
FileRecordEntity imgEntity = imgUrlMap.get(themeContent.getValue());
String extInfo = imgEntity.getExtInfo();
if (!StringUtils.isEmpty(extInfo)) {
Map<String, Object> extMap = JsonUtil.toMap(extInfo);
if (imgEntity!=null && !StringUtils.isEmpty(imgEntity.getExtInfo())) {
Map<String, Object> extMap = JsonUtil.toMap(imgEntity.getExtInfo());
ImagesDTO imagesDTO = ImagesDTO.builder().imgHeight((Integer) extMap.get("height"))
.imgWidth((Integer) extMap.get("width"))
.remark(imgEntity.getUrl())
.relId(imgEntity.getFileId())
//压缩图片
.resizeUrl(imgEntity.getUrl() + CommunityConstant.OSS_RESIZE_RATIO)
.build();
themeContent.setImgList(Collections.singletonList(imagesDTO));
}
}
} else if (themeContent.getType().equals(RelTypeEnum.MULTIPLE_IMAGE.type)) {
//多图写入图片宽高
//多图写入图片宽高,压缩图片url
List<ImagesDTO> imgList = themeContent.getImgList();
for (ImagesDTO imagesDTO : imgList) {
//压缩图片地址
imagesDTO.setResizeUrl(imagesDTO.getRemark() + CommunityConstant.OSS_RESIZE_RATIO);
if (imgUrlMap.containsKey(imagesDTO.getRelId())) {
FileRecordEntity imgEntity = imgUrlMap.get(themeContent.getValue());
FileRecordEntity imgEntity = imgUrlMap.get(imagesDTO.getRelId());
String extInfo = imgEntity.getExtInfo();
if (!StringUtils.isEmpty(extInfo)) {
Map<String, Object> extMap = JsonUtil.toMap(extInfo);
......
......@@ -7,12 +7,18 @@ import com.tanpu.community.dao.entity.community.CollectionEntity;
import com.tanpu.community.dao.entity.community.TimesCountEntity;
import com.tanpu.community.dao.mapper.community.CollectionMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@Service
......@@ -48,7 +54,7 @@ public class CollectionService {
//根据用户、主题、类型查询未删除对象
public CollectionEntity getTarget(String targetId, String userId, CollectionTypeEnum type) {
public CollectionEntity queryCollection(String targetId, String userId, CollectionTypeEnum type) {
LambdaQueryWrapper<CollectionEntity> queryWrapper = new LambdaQueryWrapper<CollectionEntity>()
.eq(CollectionEntity::getCollectionType, type.getCode())
.eq(CollectionEntity::getUserId, userId)
......@@ -57,6 +63,15 @@ public class CollectionService {
return collectionMapper.selectOne(queryWrapper);
}
//根据用户、主题、类型查询未删除对象
public CollectionEntity queryIncludeDelete(String targetId, String userId, CollectionTypeEnum type) {
LambdaQueryWrapper<CollectionEntity> queryWrapper = new LambdaQueryWrapper<CollectionEntity>()
.eq(CollectionEntity::getCollectionType, type.getCode())
.eq(CollectionEntity::getUserId, userId)
.eq(CollectionEntity::getTargetId, targetId);
return collectionMapper.selectOne(queryWrapper);
}
//根据用户、主题、类型查询未删除对象
public Set<String> getTargets(List<String> targetIds, String userId, CollectionTypeEnum type) {
if (CollectionUtils.isEmpty(targetIds)){
......@@ -91,6 +106,27 @@ public class CollectionService {
.stream().map(CollectionEntity::getTargetId).collect(Collectors.toList());
}
// 根据用户id和行为type获取target_id列表
public List<String> getListByUser(String userId, CollectionTypeEnum type,String lastId,Integer pageSize) {
LambdaQueryWrapper<CollectionEntity> queryWrapper = new LambdaQueryWrapper<CollectionEntity>()
.eq(CollectionEntity::getUserId, userId)
.eq(CollectionEntity::getCollectionType, type.getCode())
.eq(CollectionEntity::getDeleteTag, DeleteTagEnum.NOT_DELETED.getCode())
.orderByDesc(CollectionEntity::getCollectionTime);
if (StringUtils.isNotEmpty(lastId)) {
CollectionEntity target = queryIncludeDelete(lastId, userId, type);
if (target == null) return Collections.emptyList();
queryWrapper.lt(CollectionEntity::getCollectionTime, target.getCollectionTime());
}
if (pageSize != null) {
queryWrapper.last("limit " + pageSize);
}
return collectionMapper.selectList(queryWrapper)
.stream().map(CollectionEntity::getTargetId).collect(Collectors.toList());
}
// 统计单个对象(主题、评论)的数量(点赞、收藏)
public Integer getCountByTypeAndId(String targetId, CollectionTypeEnum type) {
......@@ -105,7 +141,9 @@ public class CollectionService {
if (CollectionUtils.isEmpty(targetIds)) {
return new HashMap<>();
}
LambdaQueryWrapper<CollectionEntity> queryWrapper = new LambdaQueryWrapper<CollectionEntity>().eq(CollectionEntity::getCollectionType, 1)
LambdaQueryWrapper<CollectionEntity> queryWrapper = new LambdaQueryWrapper<CollectionEntity>()
.eq(CollectionEntity::getCollectionType, type.getCode())
.eq(CollectionEntity::getDeleteTag,DeleteTagEnum.NOT_DELETED.getCode())
.in(CollectionEntity::getTargetId, targetIds).groupBy(CollectionEntity::getTargetId);
return collectionMapper.selectCountByTargetIds(queryWrapper).stream()
.collect(Collectors.toMap(TimesCountEntity::getId, TimesCountEntity::getTimes));
......@@ -123,7 +161,7 @@ public class CollectionService {
//逻辑删除,修改delete_tag
@Transactional
public void delete(String themeId, String userId, CollectionTypeEnum type) {
CollectionEntity queryCollection = getTarget(themeId, userId, type);
CollectionEntity queryCollection = queryCollection(themeId, userId, type);
if (queryCollection != null) {
queryCollection.setDeleteTag(DeleteTagEnum.DELETED.getCode());
queryCollection.setUncollectionTime(LocalDateTime.now());
......
......@@ -40,13 +40,11 @@ public class CommentService {
@Transactional
public void insertComment(CommentEntity commentEntity) {
commentEntity.setCommentId(uuidGenHelper.getUuidStr());
if (commentEntity.getContent().length()>500){
throw new IllegalArgumentException("评论内容超过500字");
}
commentMapper.insert(commentEntity);
//失效缓存
evictThemeCache(commentEntity.getThemeId());
}
......@@ -112,7 +110,7 @@ public class CommentService {
CommentEntity commentEntity = commentMapper.selectOne(new LambdaQueryWrapper<CommentEntity>()
.eq(CommentEntity::getCommentId, lastId));
if (commentEntity == null) throw new BizException("评论未找到,id:" + lastId);
queryWrapper.lt(CommentEntity::getUpdateTime, commentEntity.getCreateTime());
queryWrapper.lt(CommentEntity::getCreateTime, commentEntity.getCreateTime());
}
if (pageSize != null) {
queryWrapper.last("limit " + pageSize);
......@@ -148,8 +146,12 @@ public class CommentService {
// 失效关联主题缓存
private void evictThemeCache(String themeId){
// 评论内容
redisCache.evict(StringUtils.joinWith("_", CACHE_COMMENT_THEMEID, themeId));
// 主题内容
redisCache.evict(StringUtils.joinWith("_", CACHE_THEME_ID, themeId));
// 评论数
redisCache.evict(StringUtils.joinWith("_", THEME_COMMENT_COUNT, themeId));
}
}
package com.tanpu.community.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanpu.common.constant.BizStatus;
import com.tanpu.common.exception.BizException;
import com.tanpu.community.api.beans.req.page.Page;
import com.tanpu.community.api.enums.DeleteTagEnum;
import com.tanpu.community.dao.entity.community.FollowRelEntity;
import com.tanpu.community.dao.mapper.community.FollowRelMapper;
......@@ -21,7 +23,7 @@ public class FollowRelService {
@Resource
private FollowRelMapper followRelMapper;
public List<String> queryIdolsByFollowerId(String followerId) {
public List<String> queryIdolsByFansId(String followerId) {
return followRelMapper.selectList(new LambdaQueryWrapper<FollowRelEntity>()
.eq(FollowRelEntity::getFansId, followerId)
.eq(FollowRelEntity::getDeleteTag, DeleteTagEnum.NOT_DELETED.getCode()))
......@@ -29,19 +31,55 @@ public class FollowRelService {
.collect(Collectors.toList());
}
// @Cacheable(value = "tempCache", keyGenerator = "communityKeyGenerator")
public List<String> queryFansByIdolId(String idolId) {
public Page<String> queryIdolsByFansId(String fansId, Integer pageNum, Integer pageSize) {
Integer pageStart = (pageNum - 1) * pageSize;
List<FollowRelEntity> idols = followRelMapper.selectList(new LambdaQueryWrapper<FollowRelEntity>()
.eq(FollowRelEntity::getFansId, fansId)
.last("limit " + pageStart + ", " + pageSize)
.eq(FollowRelEntity::getDeleteTag, DeleteTagEnum.NOT_DELETED.getCode()));
List<String> list = idols.stream().map(FollowRelEntity::getIdolId)
.collect(Collectors.toList());
Integer totalSize = followRelMapper.selectCount(new LambdaQueryWrapper<FollowRelEntity>().eq(FollowRelEntity::getFansId,fansId)
.eq(FollowRelEntity::getDeleteTag, BizStatus.DeleteTag.tag_init));
Page<String> tPage = new Page<>(pageNum, pageSize, (long) totalSize, 0, list);
int totalPage = list.size() / pageSize;
if (list.size() % pageSize == 0) {
tPage.setTotalPages(totalPage);
} else {
tPage.setTotalPages(totalPage + 1);
}
return tPage;
}
public Page<String> queryFansByIdolId(String idolId, Integer pageNum, Integer pageSize) {
Integer pageStart = (pageNum - 1) * pageSize;
LambdaQueryWrapper<FollowRelEntity> queryWrapper = new LambdaQueryWrapper<FollowRelEntity>()
.eq(FollowRelEntity::getIdolId, idolId)
.last("limit " + pageStart + ", " + pageSize)
.eq(FollowRelEntity::getDeleteTag, DeleteTagEnum.NOT_DELETED.getCode());
return followRelMapper.selectList(queryWrapper)
List<String> list = followRelMapper.selectList(queryWrapper)
.stream().map(FollowRelEntity::getFansId).collect(Collectors.toList());
// 分页
Integer totalSize = followRelMapper.selectCount(new LambdaQueryWrapper<FollowRelEntity>().eq(FollowRelEntity::getIdolId, idolId)
.eq(FollowRelEntity::getDeleteTag, BizStatus.DeleteTag.tag_init));
Page<String> tPage = new Page<>(pageNum, pageSize, (long) totalSize, 0, list);
int totalPage = list.size() / pageSize;
if (list.size() % pageSize == 0) {
tPage.setTotalPages(totalPage);
} else {
tPage.setTotalPages(totalPage + 1);
}
return tPage;
}
@Transactional
public void addFollowRel(String idolId, String followerId) {
FollowRelEntity searchResult = queryRecord(idolId, followerId);
if (searchResult==null){
if (searchResult == null) {
FollowRelEntity entity = FollowRelEntity.builder()
.idolId(idolId)
.fansId(followerId)
......@@ -49,7 +87,7 @@ public class FollowRelService {
.build();
followRelMapper.insert(entity);
}else {
} else {
searchResult.setFollowTime(LocalDateTime.now());
searchResult.setDeleteTag(DeleteTagEnum.NOT_DELETED.getCode());
followRelMapper.updateById(searchResult);
......@@ -59,13 +97,14 @@ public class FollowRelService {
/**
* 逻辑删除关注关系
*
* @param idolId
* @param followerId
*/
@Transactional
public void deleteFollowRel(String idolId, String followerId) {
FollowRelEntity searchResult = queryRecord(idolId, followerId);
if (searchResult==null){
if (searchResult == null) {
throw new BizException("未找到关注关系");
}
searchResult.setUnfollowTime(LocalDateTime.now());
......@@ -73,18 +112,18 @@ public class FollowRelService {
followRelMapper.updateById(searchResult);
}
public FollowRelEntity queryRecord(String idolId, String followerId){
public FollowRelEntity queryRecord(String idolId, String followerId) {
return followRelMapper.selectOne(new LambdaQueryWrapper<FollowRelEntity>()
.eq(FollowRelEntity::getIdolId,idolId)
.eq(FollowRelEntity::getFansId,followerId));
.eq(FollowRelEntity::getIdolId, idolId)
.eq(FollowRelEntity::getFansId, followerId));
}
public boolean checkFollow(String idolId,String followerId){
public boolean checkFollow(String idolId, String followerId) {
return followRelMapper.selectCount(new LambdaQueryWrapper<FollowRelEntity>()
.eq(FollowRelEntity::getIdolId,idolId)
.eq(FollowRelEntity::getFansId,followerId)
.eq(FollowRelEntity::getDeleteTag,DeleteTagEnum.NOT_DELETED.getCode()))
>0;
.eq(FollowRelEntity::getIdolId, idolId)
.eq(FollowRelEntity::getFansId, followerId)
.eq(FollowRelEntity::getDeleteTag, DeleteTagEnum.NOT_DELETED.getCode()))
> 0;
}
......
......@@ -8,7 +8,6 @@ import com.tanpu.common.util.JsonUtil;
import com.tanpu.common.uuid.UuidGenHelper;
import com.tanpu.community.api.CommunityConstant;
import com.tanpu.community.api.enums.FileTypeEnum;
import com.tanpu.community.api.enums.OssRelType;
import com.tanpu.community.dao.entity.community.FileRecordEntity;
import com.tanpu.community.dao.mapper.community.FileRecordMapper;
import lombok.extern.slf4j.Slf4j;
......@@ -67,32 +66,34 @@ public class OSSFileService {
public FileRecordEntity uploadFile(byte[] data, String fileName, String fileSuffix, String dirPrefix) {
String[] arr = StringUtils.split(fileName, ".");
String suffix = arr[arr.length - 1];
if (FileTypeEnum.imageTypeSet.contains(suffix)) {
//上传
String id = uuidGenHelper.getUuidStr();
String key = CommunityConstant.OSS_PREFIX_FOLDER + dirPrefix + id + "." + suffix;
ossHelper.writeFile(bucketName, key, data, fileSuffix);
//落库
FileRecordEntity record = new FileRecordEntity();
record.setFileId(uuidGenHelper.getUuidStr());
record.setDeleteTag(BizStatus.DeleteTag.tag_init);
record.setFileOssKey(key);
record.setFileName(fileName);
record.setFileId(id);
record.setPreviewUrl(ossHelper.getPreSignedUrl(bucketName, key));
record.setFileType(FileTypeEnum.IMAGE.getCode());
HashMap<String, Integer> attr = getStringIntegerHashMap(data);
record.setExtInfo(JsonUtil.toJson(attr));
fileRecordMapper.insert(record);
return record;
}else {
throw new BizException("文件格式暂不支持:"+suffix);
}
//上传
String id = uuidGenHelper.getUuidStr();
String key = CommunityConstant.OSS_PREFIX_FOLDER + dirPrefix + id + "." + suffix;
ossHelper.writeFile(bucketName, key, data, fileSuffix);
//落库
FileRecordEntity record = new FileRecordEntity();
record.setFileId(uuidGenHelper.getUuidStr());
record.setDeleteTag(BizStatus.DeleteTag.tag_init);
record.setFileOssKey(key);
record.setFileName(fileName);
record.setFileId(id);
record.setPreviewUrl(ossHelper.getPreSignedUrl(bucketName, key));
record.setFileType(FileTypeEnum.IMAGE.getCode());
HashMap<String, Integer> attr = getStringIntegerHashMap(data);
record.setExtInfo(JsonUtil.toJson(attr));
fileRecordMapper.insert(record);
return record;
}
public void uploadFileNoRecord(byte[] data, String fileName, String fileSuffix, String dirPrefix) {
String[] arr = StringUtils.split(fileName, ".");
String suffix = arr[arr.length - 1];
//上传
String key = CommunityConstant.OSS_PREFIX_FOLDER + dirPrefix + suffix;
ossHelper.writeFile(bucketName, key, data, fileSuffix);
}
private HashMap<String, Integer> getStringIntegerHashMap(byte[] data) {
......
package com.tanpu.community.service;
import com.alibaba.fastjson.JSON;
import com.tanpu.common.util.JsonUtil;
import com.tanpu.community.api.beans.qo.ThemeAnalysDO;
import com.tanpu.community.api.beans.qo.TopicRankQo;
......@@ -7,16 +8,28 @@ import com.tanpu.community.api.enums.RankLogTypeEnum;
import com.tanpu.community.dao.entity.community.RankLogEntity;
import com.tanpu.community.dao.mapper.community.RankLogMapper;
import com.tanpu.community.util.BizUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@Service
public class RankLogService {
@Autowired
private OSSFileService ossFileService;
@Resource
private RankLogMapper rankLogMapper;
......@@ -25,10 +38,15 @@ public class RankLogService {
//话题排序日志
@Transactional
public void logTopicRank(List<TopicRankQo> rankList, LocalDateTime logTime, Long cost) {
if (CollectionUtils.isEmpty(rankList)) {
return;
}
Long round = rankLogMapper.selectMaxRound(RankLogTypeEnum.TOPIC.getCode());
round = round == null ? 0L : round + 1;
//分页插入
for (int i = 0; i * pageSize < rankList.size(); i++) {
int pageStart = i * pageSize;
......@@ -40,16 +58,22 @@ public class RankLogService {
.content(JsonUtil.toJson(sublist))
.pageNumber(i + 1)
.pageSize(sublist.size())
.round(round)
.build();
rankLogMapper.insert(entity);
}
}
//主题排序日志
@Transactional
public void logThemeRank(List<ThemeAnalysDO> themeList, LocalDateTime logTime, Long cost) {
if (CollectionUtils.isEmpty(themeList)) {
return;
}
Long round = rankLogMapper.selectMaxRound(RankLogTypeEnum.THEME.getCode());
round = round == null ? 0L : round + 1;
//分页插入
for (int i = 0; i * pageSize < themeList.size(); i++) {
int pageStart = i * pageSize;
......@@ -61,8 +85,46 @@ public class RankLogService {
.content(JsonUtil.toJson(sublist))
.pageNumber(i + 1)
.pageSize(sublist.size())
.round(round)
.build();
rankLogMapper.insert(entity);
}
}
// 定时清除ranklog,并上传到oss
public void clearRankLog() {
LocalDateTime t = LocalDateTime.now().minusDays(7L);
String d = t.format(DateTimeFormatter.BASIC_ISO_DATE);
log.info("start clearRankLog job before {}", d);
for (RankLogTypeEnum type : RankLogTypeEnum.values()) {
int idx = 0;
while (true) {
List<RankLogEntity> logs = rankLogMapper.selectByTypeLimit(type.getCode(), 100);
if (logs.isEmpty() || logs.get(0).getRankTime().isAfter(t)) {
break;
}
try {
String fileName = "ranklog_" + type.getCode() + "_" + idx;
ByteArrayOutputStream os = new ByteArrayOutputStream();
IOUtils.writeLines(logs.stream().map(JSON::toJSONString).collect(Collectors.toList()), null, os);
ossFileService.uploadFileNoRecord(os.toByteArray(), fileName, ".txt", "rankLog/");
Thread.sleep(1000);
} catch (Exception e) {
log.error("error in clearRankLog", e);
throw new RuntimeException(e);
}
// delete
List<Long> ids = logs.stream().map(RankLogEntity::getId).collect(Collectors.toList());
rankLogMapper.deleteBatchIds(ids);
idx++;
}
}
}
}
......@@ -15,6 +15,7 @@ import com.tanpu.community.util.TimeUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
......@@ -29,6 +30,38 @@ import static com.tanpu.community.api.constants.RedisKeyConstant.CACHE_FEIGN_USE
@Service
public class RankService {
@Value("${rank.theme.viewRate:0.1}")
public Double viewRate;
@Value("${rank.theme.forwardRate:3}")
public Double forwardRate;
@Value("${rank.theme.commentRate:2}")
public Double commentRate;
@Value("${rank.theme.likeRaten:3}")
public Double likeRaten;
@Value("${rank.theme.collectRate:3}")
public Double collectRate;
//用户质量权重
@Value("${rank.theme.userWeightRate:0.9}")
public Double userWeightRate;
//初始质量
@Value("${rank.theme.initialWeight:1.0}")
public Double initialWeight;
//时间系数
@Value("${rank.theme.timeRate:0.2}")
public Double timeRate;
@Value("${rank.topic.viewRate:1}")
public Double topicViewRate;
@Value("${rank.topic.discussRate:3}")
public Double topicDiscussRate;
@Value("${rank.topic.themeRate:1}")
public Double topicThemeRate;
//时间系数
@Value("${rank.theme.timeRate:1}")
public Double topicTimeRate;
@Autowired
private ThemeService themeService;
@Autowired
......@@ -94,9 +127,11 @@ public class RankService {
theme.setUserWeight(authorInfo.getLevelGrade() * 1.0);
}
//打分
this.calculateThemeScore(theme);
}
//打分
Map<ThemeAnalysDO, Double> map = themeAnalysDOS.stream().collect(Collectors.toMap(o -> o, ThemeAnalysDO::getRank));
//排序
Map<ThemeAnalysDO, Double> map = themeAnalysDOS.stream().collect(Collectors.toMap(o -> o, ThemeAnalysDO::getScore));
//排序
hotestThemes = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
......@@ -126,27 +161,29 @@ public class RankService {
topic.setViewCount(topicViewMap.getOrDefault(topic.getTopicId(), 0));
topic.setDisscussCount(0);
topic.setThemeWeight(0.0);
topic.setFormatViewCount(BizUtils.formatCountNumber(topic.getViewCount()));
topic.setFormatDisscussCount(BizUtils.formatCountNumber(topic.getDisscussCount()));
continue;
} else {
// 浏览量
Integer topicPV = topicViewMap.getOrDefault(topic.getTopicId(), 0);
Integer themePV = visitLogService.queryThemeVisit(themeIds);
topic.setViewCount(topicPV + themePV + topic.getViewCntAdjust());
//讨论数=发布主题贴数+回复总数
Integer commentCount = commentService.getTotalCountByThemeIds(themeIds);
topic.setDisscussCount(themeIds.size() + commentCount);
//帖子权重,求和
double themeSum = getHotestThemes().stream().filter(o -> topic.getTopicId().equals(o.getTopicId()))
.mapToDouble(ThemeAnalysDO::getScore)
.sum();
topic.setThemeWeight(themeSum);
}
// 浏览量
Integer topicPV = topicViewMap.getOrDefault(topic.getTopicId(), 0);
Integer themePV = visitLogService.queryThemeVisit(themeIds);
topic.setViewCount(topicPV + themePV + topic.getViewCntAdjust());
//讨论数=发布主题贴数+回复总数
Integer commentCount = commentService.getTotalCountByThemeIds(themeIds);
topic.setDisscussCount(themeIds.size() + commentCount);
//帖子权重,求和
double themeSum = getHotestThemes().stream().filter(o -> topic.getTopicId().equals(o.getTopicId()))
.mapToDouble(ThemeAnalysDO::getRank)
.sum();
topic.setThemeWeight(themeSum);
//格式化浏览量、讨论量
// 打分
calculateTopicScore(topic);
// 格式化浏览量、讨论量
topic.setFormatViewCount(BizUtils.formatCountNumber(topic.getViewCount()));
topic.setFormatDisscussCount(BizUtils.formatCountNumber(topic.getDisscussCount()));
}
Map<TopicRankQo, Double> map = topicRankQos.stream().collect(Collectors.toMap(o -> o, TopicRankQo::getRank));
// 排序
Map<TopicRankQo, Double> map = topicRankQos.stream().collect(Collectors.toMap(o -> o, TopicRankQo::getScore));
List<TopicRankQo> rankList = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.map(Map.Entry::getKey)
......@@ -158,7 +195,6 @@ public class RankService {
//落库
rankLogService.logTopicRank(rankList, start, TimeUtils.calMillisTillNow(start));
return;
}
/**
......@@ -214,4 +250,30 @@ public class RankService {
.collect(Collectors.toList());
}
// todo 这里用户层面只考虑了用户的gradelevel,后续可以为用户的历史贴子打分。根据用户发表的历史帖子的质量,为用户评分。例如,历史帖子的关注度,用户的粉丝数量。
// todo 可以考虑一下话题的热度。
private void calculateThemeScore(ThemeAnalysDO theme) {
// 质量=帖子质量+用户质量
double w = theme.getViewCount() * viewRate
+ theme.getForwardCount() * forwardRate
+ theme.getCommentCount() * commentRate
+ theme.getLikeCount() * likeRaten
+ theme.getCollectCount() * collectRate
+ Math.pow(theme.getUserWeight(), userWeightRate);
double score = (w + initialWeight) / Math.pow(theme.getMinutesTillNow() + 1, timeRate);
theme.setScore(score);
}
public void calculateTopicScore(TopicRankQo topic) {
//顶置话题
if (topic.getIsTop() > 0) {
topic.setScore(Double.MAX_VALUE);
}
Double socre = ((topic.getDisscussCount() * topicDiscussRate + topic.getViewCount() * topicViewRate)
/ Math.pow(topic.getMinutesTillNow() + 1, topicTimeRate))
+ topic.getThemeWeight() * topicThemeRate;
topic.setScore(socre);
}
}
......@@ -129,26 +129,28 @@ public class RecommendService {
int newTimes = newRatio;
int recTimes = pythonRatio;
String id;
while (hotTimes > 0 && hotThemeIds.size() > hotIdx) {
id = hotThemeIds.get(hotIdx);
while (newTimes > 0 && newThemeIds.size() > newIdx) {
id = newThemeIds.get(newIdx);
if (!set.contains(id)) {
result.add(id);
set.add(id);
}
hotIdx++;
hotTimes--;
newIdx++;
newTimes--;
}
while (newTimes > 0 && newThemeIds.size() > newIdx) {
id = newThemeIds.get(newIdx);
while (hotTimes > 0 && hotThemeIds.size() > hotIdx) {
id = hotThemeIds.get(hotIdx);
if (!set.contains(id)) {
result.add(id);
set.add(id);
}
newIdx++;
newTimes--;
hotIdx++;
hotTimes--;
}
while (recTimes > 0 && recThemeIds.size() > recIdx) {
id = recThemeIds.get(recIdx);
if (!set.contains(id)) {
......@@ -167,19 +169,18 @@ public class RecommendService {
// 按照 6,3,1的比例
private List<String> mergeRecommend(List<String> hotIds, List<String> newestIds, List<String> recmdIds) {
List<String> retList = new ArrayList<>();
int round = 0;
while (true) {
int hotStart = round * 6;
int newestStart = round * 3;
int recmdStart = round;
int newestStart = round * newRatio;
int hotStart = round * hotRatio;
int recmdStart = round * pythonRatio;
if (hotStart >= hotIds.size() && newestStart >= newestIds.size() && recmdStart >= recmdIds.size()) {
break;
}
retList.addAll(BizUtils.subList(hotIds, hotStart, hotStart + 6));
retList.addAll(BizUtils.subList(newestIds, newestStart, newestStart + 3));
retList.addAll(BizUtils.subList(recmdIds, recmdStart, recmdStart + 1));
retList.addAll(BizUtils.subList(newestIds, newestStart, newRatio));
retList.addAll(BizUtils.subList(hotIds, hotStart, hotRatio));
retList.addAll(BizUtils.subList(recmdIds, recmdStart, pythonRatio));
round++;
}
......
......@@ -18,8 +18,12 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@Service
......@@ -72,16 +76,22 @@ public class ThemeService {
.eq(ThemeEntity::getDeleteTag, DeleteTagEnum.NOT_DELETED.getCode()));
}
//根据id返回主题详情(未删)
public ThemeEntity queryByThemeIdIgnoreDelete(String themeId) {
return themeMapper.selectOne(new LambdaQueryWrapper<ThemeEntity>()
.eq(ThemeEntity::getThemeId, themeId));
}
//根据用户id查询主题list
public List<ThemeEntity> queryThemesByUserId(String userId, String lastId, Integer pageSize) {
public List<ThemeEntity> queryThemesByUserIdCreateDesc(String userId, String lastId, Integer pageSize) {
LambdaQueryWrapper<ThemeEntity> queryWrapper = new LambdaQueryWrapper<ThemeEntity>()
.eq(ThemeEntity::getAuthorId, userId)
.eq(ThemeEntity::getDeleteTag, DeleteTagEnum.NOT_DELETED.getCode())
.orderByDesc(ThemeEntity::getId);
.orderByDesc(ThemeEntity::getCreateTime);
if (StringUtils.isNotEmpty(lastId)) {
ThemeEntity lastEntity = queryByThemeId(lastId);
if (lastEntity == null) throw new BizException("主题未找到,id:" + lastId);
queryWrapper.lt(ThemeEntity::getUpdateTime, lastEntity.getCreateTime());
queryWrapper.lt(ThemeEntity::getCreateTime, lastEntity.getCreateTime());
}
if (pageSize != null) {
queryWrapper.last("limit " + pageSize);
......@@ -100,7 +110,7 @@ public class ThemeService {
if (StringUtils.isNotEmpty(lastId)) {
ThemeEntity lastEntity = queryByThemeId(lastId);
if (lastEntity == null) throw new BizException("主题未找到,id:" + lastId);
queryWrapper.lt(ThemeEntity::getUpdateTime, lastEntity.getCreateTime());
queryWrapper.lt(ThemeEntity::getCreateTime, lastEntity.getCreateTime());
}
if (pageSize != null) {
queryWrapper.last("limit " + pageSize);
......@@ -126,67 +136,6 @@ public class ThemeService {
}
/**
* 查询非传入作者的主题(可分页)
*
* @param lastId
* @param pageSize
* @param userId
* @return
*/
public List<ThemeEntity> selectExcludeUser(String userId, String lastId, Integer pageSize) {
LambdaQueryWrapper<ThemeEntity> queryWrapper = new LambdaQueryWrapper<>();
if (!StringUtils.isEmpty(userId)) {
queryWrapper.ne(ThemeEntity::getAuthorId, userId);
}
if (StringUtils.isNotEmpty(lastId)) {
ThemeEntity lastEntity = queryByThemeId(lastId);
if (lastEntity == null) throw new BizException("主题未找到,id:" + lastId);
queryWrapper.lt(ThemeEntity::getUpdateTime, lastEntity.getCreateTime());
}
if (pageSize != null) {
queryWrapper.last("limit " + pageSize);
}
queryWrapper.orderByDesc(ThemeEntity::getId);
queryWrapper.orderByDesc(ThemeEntity::getCreateTime);
queryWrapper.eq(ThemeEntity::getDeleteTag, DeleteTagEnum.NOT_DELETED.getCode());
return themeMapper.selectList(queryWrapper);
}
/**
* 查询非传入作者的主题(可分页)
*
* @param lastId
* @param pageSize
* @param userId
* @return
*/
public List<ThemeEntity> queryByThemeIdsExcludeUser(List<String> themeIds, String userId, String lastId, Integer pageSize) {
if (CollectionUtils.isEmpty(themeIds)) {
return Collections.emptyList();
}
LambdaQueryWrapper<ThemeEntity> queryWrapper = new LambdaQueryWrapper<ThemeEntity>()
.in(ThemeEntity::getThemeId, themeIds);
if (!StringUtils.isEmpty(userId)) {
queryWrapper.ne(ThemeEntity::getAuthorId, userId);
}
if (StringUtils.isNotEmpty(lastId)) {
ThemeEntity lastEntity = queryByThemeId(lastId);
if (lastEntity == null) throw new BizException("主题未找到,id:" + lastId);
queryWrapper.lt(ThemeEntity::getUpdateTime, lastEntity.getCreateTime());
}
if (pageSize != null) {
queryWrapper.last("limit " + pageSize);
}
queryWrapper.orderByDesc(ThemeEntity::getId);
queryWrapper.orderByDesc(ThemeEntity::getCreateTime);
queryWrapper.eq(ThemeEntity::getDeleteTag, DeleteTagEnum.NOT_DELETED.getCode());
return themeMapper.selectList(queryWrapper);
}
/**
......@@ -230,7 +179,6 @@ public class ThemeService {
if (CollectionUtils.isEmpty(userIds)){
return Collections.emptyList();
}
//TODO 索引优化
LambdaQueryWrapper<ThemeEntity> queryWrapper = new LambdaQueryWrapper<ThemeEntity>()
.in(ThemeEntity::getAuthorId, userIds)
.last("limit " + pageStart + ", " + pageSize)
......@@ -280,7 +228,7 @@ public class ThemeService {
* 查询更新节点后的用户新建主题数
*
* @param userIds 用户ids
* @param lastViewTime 更新时间节点
* @param lastId 更新时间节点
* @return
*/
public Integer queryCountFromLastId(List<String> userIds, Long lastId) {
......
......@@ -75,7 +75,10 @@ public class TopicService {
}
public TopicEntity queryById(String topicId) {
return topicMapper.selectOne(new LambdaQueryWrapper<TopicEntity>().eq(TopicEntity::getTopicId, topicId));
return topicMapper.selectOne(new LambdaQueryWrapper<TopicEntity>()
.eq(TopicEntity::getTopicId, topicId)
.eq(TopicEntity::getIsConceal, StatusEnum.FALSE)
.eq(TopicEntity::getDeleteTag, StatusEnum.FALSE));
}
public List<TopicEntity> queryByIds(List<String> topicIds) {
......
......@@ -48,6 +48,7 @@ public class VisitLogService {
.stream().map(VisitLogEntity::getRefId).distinct().collect(Collectors.toList());
return ListUtils.subtract(refIds, visited);
}
public List<String> queryUserVisited(String userId) {
List<String> visited = visitLogMapper.selectList(new LambdaQueryWrapper<VisitLogEntity>()
.eq(VisitLogEntity::getVisitorId, userId))
......@@ -58,7 +59,7 @@ public class VisitLogService {
@Transactional
public void insertOrUpdateDur(VisitLogEntity vs) {
if (visitLogMapper.selectByIdentAndRefId(vs.getIdent(), vs.getRefId()) == null) {
if (visitLogMapper.selectByIdentAndRefId(vs.getIdent(), vs.getRefId(), vs.getRefType()) == null) {
visitLogMapper.insert(vs);
} else {
visitLogMapper.updateDurByIdent(vs.getDuration(), vs.getIdent());
......@@ -92,7 +93,7 @@ public class VisitLogService {
// 查询主题 浏览量
public Integer queryThemeVisit(List<String> themes) {
if (CollectionUtils.isEmpty(themes)){
if (CollectionUtils.isEmpty(themes)) {
return 0;
}
return visitLogMapper.selectCount(new LambdaQueryWrapper<VisitLogEntity>()
......@@ -114,11 +115,11 @@ public class VisitLogService {
//统计行为集合的浏览量
public Map<String, Integer> getCountMapByTargetIds(List<String> refIds, String refType) {
if (CollectionUtils.isEmpty(refIds)){
if (CollectionUtils.isEmpty(refIds)) {
return new HashMap<>();
}
LambdaQueryWrapper<VisitLogEntity> wrapper = (new LambdaQueryWrapper<VisitLogEntity>()
.in(VisitLogEntity::getRefId,refIds))
.in(VisitLogEntity::getRefId, refIds))
.eq(VisitLogEntity::getDeleteTag, DeleteTagEnum.NOT_DELETED)
.eq(VisitLogEntity::getRefType, refType)
.groupBy(VisitLogEntity::getRefId);
......
......@@ -47,7 +47,7 @@ public class ConvertUtil {
}
ThemeAnalysDO themeAnalysDO = new ThemeAnalysDO();
BeanUtils.copyProperties(themeEntity, themeAnalysDO);
themeAnalysDO.setMinuteTillNow(TimeUtils.calMinuteTillNow(themeEntity.getCreateTime()));
themeAnalysDO.setMinutesTillNow(TimeUtils.calMinuteTillNow(themeEntity.getCreateTime()));
return themeAnalysDO;
}
......@@ -64,7 +64,8 @@ public class ConvertUtil {
BeanUtils.copyProperties(entity, qo);
// 抽取文本内容
List<ThemeContentQo> themeContentQos = JsonUtil.toBean(entity.getContent(), new TypeReference<List<ThemeContentQo>>() {});
List<ThemeContentQo> themeContentQos = JsonUtil.toBean(entity.getContent(), new TypeReference<List<ThemeContentQo>>() {
});
StringBuilder sb = new StringBuilder();
themeContentQos.stream().filter(q -> RelTypeEnum.TEXT.type.equals(q.getType())).forEach(q -> {
sb.append(q.getValue());
......@@ -88,15 +89,15 @@ public class ConvertUtil {
TopicRankQo topicRankQo = new TopicRankQo();
BeanUtils.copyProperties(topicEntity, topicRankQo);
//2小时内发帖,添加新话题标签
if(TimeUtils.calMinuteTillNow(topicEntity.getCreateTime())<120){
if (TimeUtils.calMinuteTillNow(topicEntity.getCreateTime()) < 120) {
topicRankQo.setType(TopicStatusEnum.NEWEST.getCode());
}
topicRankQo.setHoursTillNow((int) TimeUtils.calHoursTillNow(topicEntity.getCreateTime()));
topicRankQo.setMinutesTillNow((int) TimeUtils.calMinuteTillNow(topicEntity.getCreateTime()));
return topicRankQo;
}
public static List<TopicRankQo> topicEntityToHotQos(List<TopicEntity> topicEntities) {
if (topicEntities==null){
if (topicEntities == null) {
return Collections.emptyList();
}
return topicEntities.stream().map(ConvertUtil::topicEntityToHotQo).collect(Collectors.toList());
......@@ -153,13 +154,13 @@ public class ConvertUtil {
.build());
}
} else if ((content.getType().equals(RelTypeEnum.SINGLE_IMG.type))) {
if (StringUtils.isEmpty(content.getValue())){
if (StringUtils.isEmpty(content.getValue())) {
list.add(ThemeAttachmentEntity.builder()
.attachType(Integer.valueOf(content.getType()))
.attachId(content.getValue())
.themeId(themeId)
.build());
}else {
} else {
List<ImagesDTO> imgList = content.getImgList();
for (ImagesDTO imagesDTO : imgList) {
list.add(ThemeAttachmentEntity.builder()
......@@ -170,7 +171,7 @@ public class ConvertUtil {
}
}
} else {
} else {
}
}
......@@ -211,9 +212,9 @@ public class ConvertUtil {
.build();
}
public static FileUploadResp fileRecordEntity2Resp(FileRecordEntity entity){
public static FileUploadResp fileRecordEntity2Resp(FileRecordEntity entity) {
FileUploadResp resp = new FileUploadResp();
BeanUtils.copyProperties(entity,resp);
BeanUtils.copyProperties(entity, resp);
String extInfo = entity.getExtInfo();
if (!StringUtils.isEmpty(extInfo)) {
Map<String, Object> extMap = JsonUtil.toMap(extInfo);
......@@ -224,5 +225,4 @@ public class ConvertUtil {
}
}
......@@ -12,12 +12,14 @@ import java.util.List;
* @email: zhoupeng@wealthgrow.cn
*/
public class PageUtils {
public static <T> Page<T> page(Pageable pageable, List<T> list) {
if (CollectionUtils.isEmpty(list)) {
if(pageable==null){
return new Page<T>(1,0, (long)list.size(),1, list);
}
return new Page<>(pageable, 0L, new ArrayList<>());
return new Page<T>(pageable, 0L, new ArrayList<>());
} else {
if(pageable==null){
return new Page<T>(1,list.size(), (long)list.size(),1, list);
......@@ -64,4 +66,8 @@ public class PageUtils {
}
}
}
public static <T> Page<T> page(Page<String> o, List<T> list) {
return new Page<>(o.getPageNum(),o.getPageSize(),o.getTotalSize(),o.getTotalPages(),list);
}
}
......@@ -11,7 +11,7 @@ public class RankUtils {
/**
* 根据id排序主题对象
* 根据id排序主题对象(同时去重)
* @param list 主题
* @param ids 主题Id,list中可重复
* @return
......
......@@ -37,6 +37,11 @@ public class TimeUtils {
return start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
}
//格式化时间
public static String format(LocalDateTime start) {
return start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
}
//计算迄今分钟
public static long calMinuteTillNow(LocalDateTime start) {
Duration between = Duration.between(start, LocalDateTime.now());
......@@ -55,7 +60,7 @@ public class TimeUtils {
return between.toDays();
}
//计算迄今
//计算迄今小时
public static long calHoursTillNow(LocalDateTime start) {
Duration between = Duration.between(start, LocalDateTime.now());
return between.toHours();
......
......@@ -14,19 +14,19 @@ server:
spring.datasource:
community:
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://rm-uf6r22t3d798q4kmkao.mysql.rds.aliyuncs.com:3306/tamp_community?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull
username: tamp_admin
password: '@imeng123'
maxActive: 2
minIdle: 2
initialSize: 2
user:
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://rm-uf6r22t3d798q4kmkao.mysql.rds.aliyuncs.com:3306/tamp_user?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull
password: '@imeng123'
jdbc-url: jdbc:mysql://rm-uf6lqwk9969zao53uro.mysql.rds.aliyuncs.com:3306/tamp_community?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull
username: dev
password: 'qimeng123'
maxActive: 2
minIdle: 2
initialSize: 2
# user:
# driver-class-name: com.mysql.cj.jdbc.Driver
# jdbc-url: jdbc:mysql://rm-uf6r22t3d798q4kmkao.mysql.rds.aliyuncs.com:3306/tamp_user?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull
# password: '@imeng123'
# maxActive: 2
# minIdle: 2
# initialSize: 2
spring.redis:
host: 118.190.63.109
......@@ -64,8 +64,11 @@ spring.kafka:
spring:
sleuth:
enabled: false
sampler.probability: 1.0
zipkin:
enabled: false
base-url: http://tracing-analysis-dc-sh.aliyuncs.com/adapt_f582gdhpd0@141b989b3abcccb_f582gdhpd0@53df7ad2afe8301_prod
sender.type: web
aliyun:
oss:
......@@ -94,4 +97,20 @@ recommend:
python: 1
python:
enable: false
url: http://172.168.0.164:9000/api/get_recommend?user_id=2431614397151511
\ No newline at end of file
url: http://172.168.0.164:9000/api/get_recommend?user_id=2431614397151511
rank:
theme:
viewRate: 0.1
forwardRate: 3
commentRate: 2
likeRaten: 1
collectRate: 3
userWeightRate: 0.9
initialWeight: 1.0
timeRate: 0.2
topic:
viewRate: 2
discussRate: 3
themeRate: 3
timeRate: 1
......@@ -15,7 +15,7 @@ server:
spring.datasource:
community:
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://rm-uf6r22t3d798q4kmk.mysql.rds.aliyuncs.com:3306/tamp_community?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull
jdbc-url: jdbc:mysql://rm-uf6r22t3d798q4kmkao.mysql.rds.aliyuncs.com:3306/tamp_community?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull
username: tamp_admin
password: '@imeng123'
maxActive: 2
......@@ -23,7 +23,8 @@ spring.datasource:
initialSize: 2
user:
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://rm-uf6r22t3d798q4kmk.mysql.rds.aliyuncs.com:3306/tamp_user?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull
jdbc-url: jdbc:mysql://rm-uf6r22t3d798q4kmkao.mysql.rds.aliyuncs.com:3306/tamp_user?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull
username: tamp_admin
password: '@imeng123'
maxActive: 2
minIdle: 2
......@@ -80,6 +81,7 @@ es:
port: 9200
userName: 1
userPasswd: 2
index: test
tencent:
cloud:
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment