Quellcode durchsuchen

标签库/后台跳转

todo
//redis配置文件从配置中心配
zhijiezhao vor 2 Jahren
Ursprung
Commit
4a2f620bd5

+ 7 - 0
pom.xml

@@ -170,6 +170,13 @@
             <version>3.0.0</version>
         </dependency>
 
+        <!--  登陆新后台用   -->
+        <dependency>
+            <groupId>io.jsonwebtoken</groupId>
+            <artifactId>jjwt</artifactId>
+            <version>0.9.1</version>
+        </dependency>
+
 		<dependency>
 			<groupId>org.springframework.boot</groupId>
 			<artifactId>spring-boot-starter-test</artifactId>

+ 19 - 5
src/main/java/com/caimei365/tools/controller/BaseApi.java

@@ -1,9 +1,11 @@
 package com.caimei365.tools.controller;
 
+import com.caimei365.tools.model.ResponseJson;
 import com.caimei365.tools.service.CmBehaviorRecordService;
 import com.caimei365.tools.service.CmOrganValueSystemService;
 import com.caimei365.tools.service.CmRepurchaseFrequencyService;
 import com.caimei365.tools.service.CmVipCouponService;
+import com.caimei365.tools.service.impl.SysUserServiceImpl;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.java.Log;
 import lombok.extern.slf4j.Slf4j;
@@ -14,6 +16,7 @@ import org.springframework.web.bind.annotation.RestController;
 
 import javax.annotation.Resource;
 import java.io.IOException;
+import java.util.List;
 
 /**
  * Description
@@ -29,21 +32,32 @@ public class BaseApi {
 
     @Resource
     private CmOrganValueSystemService cmOrganValueSystemService;
-    @Resource private CmRepurchaseFrequencyService cmRepurchaseFrequencyService;
-    @Resource private CmBehaviorRecordService cmBehaviorRecordService;
-    @Resource private CmVipCouponService cmVipCouponService;
+    @Resource
+    private CmRepurchaseFrequencyService cmRepurchaseFrequencyService;
+    @Resource
+    private CmBehaviorRecordService cmBehaviorRecordService;
+    @Resource
+    private CmVipCouponService cmVipCouponService;
+    @Resource
+    private SysUserServiceImpl sysUserService;
 
     @Value(value = "${swagger.enabled}")
     private Boolean swaggerEnabled;
 
+
     @GetMapping("")
-    public String welcome(){
-        if (swaggerEnabled){
+    public String welcome() {
+        if (swaggerEnabled) {
             return "欢迎使用!<br><a href='http://47.119.112.46:18013/doc.html'>doc接口文档入口(beta)</a><br><a href='http://47.119.112.46:18013/swagger-ui/index.html'>swagger接口文档入口(beta)</a>";
         }
         return "欢迎使用!";
     }
 
+    @GetMapping("/new/token")
+    public String getNewToken(String id) {
+        return sysUserService.getNewToken(id);
+    }
+
     /**
      * 临时接口
      */

+ 17 - 1
src/main/java/com/caimei365/tools/mapper/BaseMapper.java

@@ -5,6 +5,7 @@ import com.caimei365.tools.model.bo.HeheCouponBo;
 import com.caimei365.tools.model.po.LogisticsInfoPo;
 import com.caimei365.tools.model.po.SearchFrequencyVo;
 import com.caimei365.tools.model.po.SuperVipPo;
+import com.caimei365.tools.model.po.SysUser;
 import org.apache.ibatis.annotations.Mapper;
 import org.apache.ibatis.annotations.Param;
 
@@ -94,7 +95,6 @@ public interface BaseMapper {
      */
     void insertProductViews(Integer productId, Integer views, Date viewTime);
 
-
     List<SearchFrequencyVo> getInfoBykeyword(String keyword, Integer fromSearch, Integer trueStutas);
 
     void saveInfo(SearchFrequencyVo searchFrequencyVo);
@@ -102,4 +102,20 @@ public interface BaseMapper {
     void upFrequencyById(Integer id, Integer frequency);
 
     void uplinkageFrequencyById(Integer id, Integer linkageFrequency, Integer frequency, Integer delStatus);
+
+    Integer findKeywordId(String keyword);
+
+    void updateKeywordTimes(Integer id);
+
+    void insertLabelSource(SearchFrequencyVo sea);
+
+    void updateAllKeyword();
+
+    List<Integer> getRecommendKeyword(String date);
+
+    void updateRecommend(List<Integer> ids);
+
+    SysUser findUserNameById(String id);
+
+    List<String> getRoleNamesByUserId(Integer id);
 }

+ 6 - 6
src/main/java/com/caimei365/tools/model/po/SearchFrequencyVo.java

@@ -6,27 +6,27 @@ import java.sql.Timestamp;
 
 @Data
 public class SearchFrequencyVo {
-       private Integer  id ;
+    private Integer id;
     /**
      * 数据来源(1:首页;2:信息中心)
      */
-    private Integer fromSearch   ;
+    private Integer fromSearch;
     /**
      * 接口路径
      */
-    private String  path;
+    private String path;
     /**
      * 关键词
      */
-    private String  keyword ;
+    private String keyword;
     /**
      * 关键词出现次数
      */
-    private Integer  frequency ;
+    private Integer frequency;
     /**
      * 搜索时间
      */
-    private Timestamp searchTime ;
+    private Timestamp searchTime;
     /**
      * 0:未加入关键词库;1:已加入关键词库
      */

+ 16 - 0
src/main/java/com/caimei365/tools/model/po/SysUser.java

@@ -0,0 +1,16 @@
+package com.caimei365.tools.model.po;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/**
+ * @author zzj
+ */
+@Data
+@AllArgsConstructor
+@NoArgsConstructor
+public class SysUser {
+    private String userName;
+    private Integer id;
+}

+ 4 - 0
src/main/java/com/caimei365/tools/service/ProductService.java

@@ -10,4 +10,8 @@ import org.springframework.stereotype.Service;
  */
 public interface ProductService {
     void conKeyword(Integer fromType, String path, String keyword, String linkageFlag);
+
+    void updateAllKeyword();
+
+    void updateKeywordRecommend();
 }

+ 8 - 0
src/main/java/com/caimei365/tools/service/SysUserService.java

@@ -0,0 +1,8 @@
+package com.caimei365.tools.service;
+
+/**
+ * @author zzj
+ */
+public interface SysUserService {
+    public String getNewToken(String id);
+}

+ 33 - 47
src/main/java/com/caimei365/tools/service/impl/ProductServiceImpl.java

@@ -33,53 +33,39 @@ public class ProductServiceImpl implements ProductService {
      */
     @Override
     public void conKeyword(Integer fromType, String path, String keyword, String linkageFlag) {
-        Date date = new Date();
-        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-        sd.format(date);
-        Calendar cal = Calendar.getInstance();
-        cal.setTime(date);
-        //根据关键词和来源查询数据库是否存在(存在来源也相同时增加次数,存在但来源不同时和不存在则新增)
-        List<SearchFrequencyVo> searchFrequencyVoList = baseMapper.getInfoBykeyword(keyword, fromType, 0);
-        if (null != searchFrequencyVoList && searchFrequencyVoList.size() > 0) {
-            //判断是否有加入关键词的(有则判断是否联动,无则搜索次数加1)
-            List<SearchFrequencyVo> searchFrequencyVoAll = baseMapper.getInfoBykeyword(keyword, fromType, 1);
-            if (null != searchFrequencyVoAll && searchFrequencyVoAll.size() > 0) {
-                //判断是否是关键词联动搜索
-                if (StringUtils.isNotEmpty(linkageFlag) && "1".equals(linkageFlag)) {
-                    //联动次数加1,搜索次数重置,从新出现在关键词列表
-                    Integer linkageFrequency = searchFrequencyVoAll.get(0).getLinkageFrequency() + 1;
-                    Integer frequency = 0;
-                    Integer delStatus = 1;
-                    baseMapper.uplinkageFrequencyById(searchFrequencyVoAll.get(0).getId(), linkageFrequency, frequency, delStatus);
-                } else {
-                    Integer frequency = searchFrequencyVoList.get(0).getFrequency() + 1;
-                    baseMapper.upFrequencyById(searchFrequencyVoList.get(0).getId(), frequency);
-                }
-            } else {
-                Integer frequency = searchFrequencyVoList.get(0).getFrequency() + 1;
-                baseMapper.upFrequencyById(searchFrequencyVoList.get(0).getId(), frequency);
-            }
-        } else {
-            //不存在 新增
-            //判断是否联动
-            //判断是否是关键词联动搜索
-            List<SearchFrequencyVo> searchFrequencyVoAll = baseMapper.getInfoBykeyword(keyword, fromType, 1);
-            if (StringUtils.isNotEmpty(linkageFlag) && "1".equals(linkageFlag)) {
-                //联动次数加1,搜索次数重置,从新出现在关键词列表
-                Integer linkageFrequency = searchFrequencyVoAll.get(0).getLinkageFrequency() + 1;
-                Integer frequency = 0;
-                Integer delStatus = 1;
-                baseMapper.uplinkageFrequencyById(searchFrequencyVoAll.get(0).getId(), linkageFrequency, frequency, delStatus);
-            } else {
-                SearchFrequencyVo sea = new SearchFrequencyVo();
-                sea.setKeyword(keyword);
-                sea.setFrequency(1);
-                sea.setLinkageFrequency(0);
-                sea.setPath(path);
-                sea.setFromSearch(fromType);
-                sea.setSearchTime(new java.sql.Timestamp(cal.getTime().getTime()));
-                baseMapper.saveInfo(sea);
-            }
+        /**
+         * 关键词库v1.1
+         * 任意符合条件的记录直接插入cm_label_source,保留元数据一年
+         * cm_user_search_frequency中keyword为唯一,表中已有添加一次frequency,表中没有则新增,修改时刷新searchTime 最近一次搜索时间
+         */
+        SearchFrequencyVo sea = new SearchFrequencyVo();
+        Integer id = baseMapper.findKeywordId(keyword);
+        if (null != id) {
+            //已存在改次数,不存在插入
+            baseMapper.updateKeywordTimes(id);
+            sea.setId(id);
+        }else{
+            sea.setFrequency(1);
+            sea.setKeyword(keyword);
+            baseMapper.saveInfo(sea);
         }
+        sea.setPath(path);
+        baseMapper.insertLabelSource(sea);
+    }
+
+    @Override
+    public void updateAllKeyword() {
+       baseMapper.updateAllKeyword();
+    }
+
+    @Override
+    public void updateKeywordRecommend() {
+        //查询本周时间内搜索大于等于三次的
+        Calendar instance = Calendar.getInstance();
+        instance.setTime(new Date());
+        instance.add(Calendar.WEEK_OF_MONTH,-1);
+        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        List<Integer> ids = baseMapper.getRecommendKeyword(format.format(instance.getTime()));
+        baseMapper.updateRecommend(ids);
     }
 }

+ 62 - 0
src/main/java/com/caimei365/tools/service/impl/SysUserServiceImpl.java

@@ -0,0 +1,62 @@
+package com.caimei365.tools.service.impl;
+
+import com.caimei365.tools.mapper.BaseMapper;
+import com.caimei365.tools.model.po.SysUser;
+import com.caimei365.tools.service.SysUserService;
+import com.caimei365.tools.utils.RedisService;
+import com.caimei365.tools.utils.constant.ConstantKey;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.SignatureAlgorithm;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * @author zzj
+ */
+@Service
+@Slf4j
+public class SysUserServiceImpl implements SysUserService {
+
+    @Resource
+    private BaseMapper baseMapper;
+
+    @Resource
+    private RedisService redisService;
+
+    @Override
+    public String getNewToken(String id) {
+        SysUser user = baseMapper.findUserNameById(id);
+        List<String> roleListByUserId = baseMapper.getRoleNamesByUserId(user.getId());
+        String token = createToken(user.getUserName(), roleListByUserId);
+        log.info("token-----------------------" + token);
+        return token;
+    }
+
+    public String createToken(String username, List<String> roleList) {
+        Calendar calendar = Calendar.getInstance();
+        // 设置签发时间
+        calendar.setTime(new Date());
+        Date now = calendar.getTime();
+        // 设置过期时间
+        calendar.add(Calendar.MINUTE, ConstantKey.TOKEN_EXPIRE);
+        Date time = calendar.getTime();
+        String token = Jwts.builder()
+                .setSubject(username + "-" + roleList)
+                // 签发时间
+                .setIssuedAt(now)
+                // 过期时间
+                .setExpiration(time)
+                // 自定义算法与签名:这里算法采用HS512,常量中定义签名key
+                .signWith(SignatureAlgorithm.HS512, ConstantKey.SIGNING_KEY)
+                .compact();
+        // 将token存入redis,并设置超时时间为token过期时间
+        long expire = time.getTime() - now.getTime();
+        redisService.set(token, token, expire);
+        return token;
+    }
+}

+ 56 - 0
src/main/java/com/caimei365/tools/task/KeywordLabelTask.java

@@ -0,0 +1,56 @@
+package com.caimei365.tools.task;
+
+import com.caimei365.tools.service.ProductService;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.scheduling.annotation.EnableScheduling;
+import org.springframework.scheduling.annotation.Scheduled;
+
+import javax.annotation.Resource;
+
+/**
+ * @author zzj
+ */
+@Slf4j
+@Configuration
+@EnableScheduling
+@RequiredArgsConstructor
+public class KeywordLabelTask {
+
+    @Resource
+    private ProductService productService;
+    /**
+     * 1.关键词每周仅推荐一次;
+     *
+     * 2.当前本周内,用户搜索次数≥3次时,则立刻进行推荐,当推荐一次后,且本周内无需再推荐;
+     *
+     * 3.当上一周的关键词搜索次数未满足推荐条件时,则无需累计到下周计算搜索次数,且下一周需重新计算;
+     *
+     * 4.如关键词已被推荐过,且没有加入到标签库的,则在下一周满搜索条件时即重新推荐一次,依此类推;
+     *
+     * 5.已推荐过的关键词在未处理的情况下,又再次进行推荐时,则进行清除,保留最新的一次推荐记录;
+     *
+     * 6.当关键词已加入到标签库的,则无需再进行推荐;
+     *
+     * 7.当前关键词在关键搜索推荐被加入标签库后,这里的加入标签库按钮也许同步隐藏,标签库状态变为已添加;
+     *
+     * 8.被推荐的关键词如半年内未处理的,则进行清除;
+     *
+     *
+     *
+     *
+     * 每周星期天晚11点实行一次
+     * 把cm_user_search_frequency未加入标签库的全表置为未推荐,忽略置为未忽略
+     * 查询cm_label_source是否存在本周内已查询三次置为推荐
+     *
+     */
+    @Scheduled(cron = "* * 23 * * 1")
+    public void checkKeyword() {
+        //把cm_user_search_frequency未加入标签库的全表置为未推荐,忽略置为未忽略
+        productService.updateAllKeyword();
+        //查询满足搜索条件的,修改推荐标记
+        productService.updateKeywordRecommend();
+    }
+
+}

+ 85 - 0
src/main/java/com/caimei365/tools/utils/RedisService.java

@@ -0,0 +1,85 @@
+package com.caimei365.tools.utils;
+
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.ValueOperations;
+import org.springframework.stereotype.Service;
+import org.springframework.util.StringUtils;
+
+import javax.annotation.Resource;
+import java.io.Serializable;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Redis 服务工具类
+ *
+ * @author : Charles
+ * @date : 2021/12/10
+ */
+@Service
+public class RedisService {
+    @Resource
+    private RedisTemplate<Serializable, Object> redisTemplate;
+    /**
+     * 读取缓存
+     */
+    public Object get(String key) {
+        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
+        return operations.get(key);
+    }
+    /**
+     * 判断缓存中是否存在
+     */
+    public boolean exists(String key) {
+        return StringUtils.hasLength(key) && Boolean.TRUE.equals(redisTemplate.hasKey(key));
+    }
+    /**
+     * 删除缓存
+     */
+    public void remove(String key) {
+        if (exists(key)) {
+            redisTemplate.delete(key);
+        }
+    }
+    /**
+     * 写入缓存
+     */
+    public boolean set(String key, Object value) {
+        boolean result = false;
+        try {
+            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
+            operations.set(key, value);
+            result = true;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return result;
+    }
+    /**
+     * 写入缓存 并 加上过期时间(毫秒)
+     */
+    public boolean set(String key, Object value, Long expireTimeMillis) {
+        boolean result = false;
+        try {
+            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
+            operations.set(key, value);
+            redisTemplate.expire(key, expireTimeMillis, TimeUnit.MILLISECONDS);
+            result = true;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return result;
+    }
+    /**
+     * 写入过期时间(毫秒)
+     */
+    public boolean expire(String key, Long expireTimeMillis) {
+        boolean result = false;
+        try {
+            redisTemplate.expire(key, expireTimeMillis, TimeUnit.MILLISECONDS);
+            result = true;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return result;
+    }
+}

+ 22 - 0
src/main/java/com/caimei365/tools/utils/constant/ConstantKey.java

@@ -0,0 +1,22 @@
+package com.caimei365.tools.utils.constant;
+
+/**
+ * Description
+ *
+ * @author : Charles
+ * @date : 2021/12/2
+ */
+public class ConstantKey {
+    /**
+     * 签名key
+     */
+    public static final String SIGNING_KEY = "Charles@Jwt!&Secret^#";
+    /**
+     * Token存入header的键名
+     */
+    public static final String TOKEN_NAME = "X-Token";
+    /**
+     * Token过期时间(分钟)
+     */
+    public static final Integer TOKEN_EXPIRE = 30;
+}

+ 20 - 1
src/main/resources/bootstrap.yml

@@ -29,4 +29,23 @@ spring:
       mail.smtp.starttls.enable: true
       mail.smtp.starttls.required: true
       mail.smtp.ssl.enable: true
-      mail.display.sendmail: spring-boot-demo
+      mail.display.sendmail: spring-boot-demo
+  #数据源连接--end
+  redis:
+    host: 172.31.165.27
+    port: 6379
+    password: 6#xsI%b4o@5c3RoE
+    #Redis数据库索引(默认为0)
+    database: 0
+    #连接池最大连接数(使用负值表示没有限制)
+    jedis:
+      pool:
+        max-active: 50
+        #连接池最大阻塞等待时间(使用负值表示没有限制)
+        max-wait: 3000
+        #连接池中的最大空闲连接
+        max-idle: 20
+        #连接池中的最小空闲连接
+        min-idle: 2
+    #连接超时时间(毫秒)
+    timeout: 5000

+ 62 - 4
src/main/resources/mapper/BaseMapper.xml

@@ -125,7 +125,6 @@
     <select id="getInfoBykeyword" resultType="com.caimei365.tools.model.po.SearchFrequencyVo">
         select id,
                fromSearch,
-               path,
                keyword,
                frequency,
                searchTime,
@@ -137,6 +136,27 @@
           and trueStatus = #{trueStutas}
     </select>
 
+    <select id="findKeywordId" resultType="java.lang.Integer">
+        select id
+        from cm_user_search_frequency
+        where keyword = #{keyword}
+          and delStatus = 1
+        limit 1
+    </select>
+
+    <select id="findUserNameById" resultType="com.caimei365.tools.model.po.SysUser">
+        select ssr.systemId as id,su.username as username
+        from sys_system_role ssr
+                 left join system_user su on ssr.systemId=su.id
+        where ssr.sysId=#{id}
+    </select>
+
+    <select id="getRoleNamesByUserId" resultType="java.lang.String">
+        SELECT DISTINCT r.role_name FROM system_role r
+        LEFT JOIN system_role_user ru ON r.id = ru.role_id
+        WHERE ru.user_id = #{userId}
+    </select>
+
     <update id="upFrequencyById">
         update cm_user_search_frequency
         set frequency=#{frequency},
@@ -152,8 +172,46 @@
         where id = #{id}
     </update>
 
-    <insert id="saveInfo" parameterType="com.caimei365.tools.model.po.SearchFrequencyVo">
-        insert into cm_user_search_frequency(fromSearch, path, keyword, frequency, searchTime, linkageFrequency)
-        values (#{fromSearch}, #{path}, #{keyword}, #{frequency}, #{searchTime}, #{linkageFrequency})
+    <update id="updateKeywordTimes">
+        UPDATE cm_user_search_frequency
+        SET frequency  = frequency + 1,
+            searchtime = NOW()
+        WHERE id = #{id}
+    </update>
+
+    <update id="updateAllKeyword">
+        update cm_user_search_frequency
+        set recommendFlag=0,
+            recommendStatus=0
+        where trueStatus = 0
+          and delStatus = 1
+    </update>
+
+    <update id="getRecommendKeyword">
+        SELECT keyWordId
+        FROM cm_label_source
+        WHERE saveTime BETWEEN #{date} AND NOW()
+        GROUP BY keyWordId
+        HAVING COUNT(keywordId) > 1
+    </update>
+
+    <update id="updateRecommend">
+        update cm_user_search_frequency
+        set recommendStatus = 1
+        where id in
+        <foreach collection="ids" separator="," item="id" open="(" close=")">
+            #{id}
+        </foreach>
+    </update>
+
+    <insert id="saveInfo" parameterType="com.caimei365.tools.model.po.SearchFrequencyVo" useGeneratedKeys="true"
+            keyProperty="id">
+        insert into cm_user_search_frequency(keyword, frequency, searchTime)
+        values (#{keyword}, #{frequency}, now())
+    </insert>
+
+    <insert id="insertLabelSource">
+        insert into cm_label_source(keywordId, saveTime, path)
+        VALUES (#{id}, now(), #{path})
     </insert>
 </mapper>