Pārlūkot izejas kodu

统计前一天商品详情访问量

chao 3 gadi atpakaļ
vecāks
revīzija
0f435d3b8a

+ 15 - 0
pom.xml

@@ -117,6 +117,21 @@
             <artifactId>rocketmq-spring-boot-starter</artifactId>
             <version>2.2.0</version>
         </dependency>
+        <!-- redis依赖包 -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-redis</artifactId>
+            <exclusions>
+                <exclusion>
+                    <groupId>io.lettuce</groupId>
+                    <artifactId>lettuce-core</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        <dependency>
+            <groupId>redis.clients</groupId>
+            <artifactId>jedis</artifactId>
+        </dependency>
 
         <!-- knife4j:swagger增强-->
         <!-- https://doc.xiaominfo.com/knife4j/documentation/get_start.html -->

+ 8 - 0
src/main/java/com/caimei365/tools/mapper/BaseMapper.java

@@ -73,4 +73,12 @@ public interface BaseMapper {
      * @param count  增加条数
      */
     void updateSmsSendCount(int markId, int count);
+
+    /**
+     * 统计前一天商品访问量
+     * @param productId 商品Id
+     * @param views     访问量
+     * @param countTime 访问日期(天)
+     */
+    void insertProductViews(Integer productId, Integer views, Date countTime);
 }

+ 307 - 0
src/main/java/com/caimei365/tools/service/RedisService.java

@@ -0,0 +1,307 @@
+package com.caimei365.tools.service;
+
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang.StringUtils;
+import org.springframework.data.redis.core.HashOperations;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.ValueOperations;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.io.Serializable;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Redis 服务工具类
+ *
+ * @author : Charles
+ * @date : 2021/3/4
+ */
+@Slf4j
+@Service
+public class RedisService {
+
+	@Resource
+	private RedisTemplate<Serializable, Object> redisTemplate;
+
+    /**
+     * 批量删除
+     * @param keys
+     */
+	public void remove(String... keys) {
+		for(String key :keys){
+			remove(key);
+		}
+	}
+
+    /**
+     * 批量删除正则匹配到的
+     * @param pattern
+     */
+	public void removePattern(String pattern) {
+		Set<Serializable> keys = redisTemplate.keys(pattern);
+        assert keys != null;
+        if (keys.size() > 0){
+			redisTemplate.delete(keys);
+		}
+	}
+
+    /**
+     * 删除
+     * @param key
+     */
+	public void remove(String key) {
+		if (exists(key)) {
+			redisTemplate.delete(key);
+		}
+	}
+
+    /**
+     * 判断缓存中是否存在
+     * @param key
+     * @return boolean
+     */
+	public boolean exists(String key) {
+		return StringUtils.isBlank(key) ? false : redisTemplate.hasKey(key);
+	}
+
+    /**
+     * 读取缓存
+     * @param key
+     * @return
+     */
+	public Object get(String key) {
+		Object result = null;
+		ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
+		result = operations.get(key);
+		return result;
+	}
+
+	/**
+	 * 读取缓存hash【hgetall】
+	 * @param key
+	 * @return
+	 */
+	public Map<Object, Object> hgetall(String key) {
+		Map<Object, Object> result = null;
+		HashOperations<Serializable, Object, Object> operations = redisTemplate.opsForHash();
+		result = operations.entries(key);
+		return result;
+	}
+
+    /**
+     * 写入缓存
+     * @param key
+     * @param value
+     * @return
+     */
+	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;
+	}
+
+    /**
+     * 写入缓存并加上过期时间(秒)
+     * @param key
+     * @param value
+     * @param expireTimeSeconds
+     * @return
+     */
+	public boolean set(String key, Object value, Long expireTimeSeconds) {
+		boolean result = false;
+		try {
+			ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
+			operations.set(key, value);
+			redisTemplate.expire(key, expireTimeSeconds, TimeUnit.SECONDS);
+			result = true;
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return result;
+	}
+    /**
+     * 写入过期时间(秒)
+     * @param key
+     * @param expireTimeSeconds
+     * @return
+     */
+	public boolean expire(String key, Long expireTimeSeconds) {
+		boolean result = false;
+		try {
+			redisTemplate.expire(key, expireTimeSeconds, TimeUnit.SECONDS);
+			result = true;
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return result;
+	}
+    /* **************************** 针对list操作的方法 **************************** */
+    /**
+     * 在key对应list的尾部添加
+     * @param key
+     * @param value
+     * @return
+     */
+	public long rightPushForList(String key, Object value) {
+		return redisTemplate.opsForList().rightPush(key, value);
+	}
+
+    /**
+     * 在key对应list的头部添加
+     * @param key
+     * @param value
+     * @return
+     */
+	public long leftPushForList(String key, Object value) {
+		return redisTemplate.opsForList().leftPush(key, value);
+	}
+
+    /**
+     * key对应list的长度
+     * @param key
+     * @return
+     */
+	public long listSize(String key) {
+		return redisTemplate.opsForList().size(key);
+	}
+
+    /**
+     * 获取list集合
+     * @param Key
+     * @param begin
+     * @param end
+     * @return
+     */
+	public List<?> getList(String Key, int begin, int end) {
+		return redisTemplate.opsForList().range(Key, begin, end);
+	}
+
+    /**
+     * 在key对应list的尾部移除
+     * @param key
+     * @return
+     */
+	public Object rightPopForList(String key) {
+		return redisTemplate.opsForList().rightPop(key);
+	}
+
+    /**
+     * 在key对应list的头部移除
+     * @param key
+     * @return
+     */
+	public Object leftPopForList(String key) {
+		return redisTemplate.opsForList().leftPop(key);
+	}
+
+    /**
+     * 移除list的index位置上的值
+     * @param Key
+     * @param index
+     * @param value
+     */
+	public void removeList(String Key, long index, Object value) {
+		redisTemplate.opsForList().remove(Key, index, value);
+	}
+
+    /**
+     * 重置list的index位置上的值
+     * @param Key
+     * @param index
+     * @param value
+     */
+	public void setList(String Key, long index, Object value) {
+		redisTemplate.opsForList().set(Key, index, value);
+	}
+
+
+    /**
+     * 写入list
+     * @param key
+     * @param list
+     */
+	public void setList(String key, List list) {
+		if(list!=null&&list.size()>0){
+			for (Object object : list) {
+				rightPushForList(key,object);
+			}
+		}
+	}
+
+    /**
+     * 写入map
+     * @param key
+     * @param map
+     */
+	public void setMap(String key, Map<String, Object> map) {
+		redisTemplate.opsForHash().putAll(key, map);
+	}
+
+    /**
+     * 获取map
+     * @param key
+     * @param mapKey
+     * @return
+     */
+	public Object get(String key, String mapKey) {
+		return redisTemplate.opsForHash().get(key, mapKey);
+	}
+
+    /**
+     * 写入map
+     * @param key
+     * @param hashKey
+     * @param hashValue
+     */
+	public void setMapByKV(String key, Object hashKey, Object hashValue) {
+		redisTemplate.opsForHash().put(key, hashKey,hashValue);
+	}
+
+    /**
+     * 删除map中的某个key-value
+     * @param key
+     * @param hashKey
+     */
+	public void removeHash(String key, String hashKey) {
+		redisTemplate.opsForHash().delete(key, hashKey);
+	}
+
+    /**
+     *
+     * @param key
+     * @return
+     */
+	public Map<Object, Object> getEntries(String key) {
+		return redisTemplate.opsForHash().entries(key);
+	}
+
+    /**
+     *
+     * @param key
+     * @param step
+     * @return
+     */
+	public long increase(String key, long step) {
+		return redisTemplate.opsForValue().increment(key, step);
+	}
+
+    /**
+     * 获取失效时间
+     * @param key
+     * @return
+     */
+	public long getExpireTime(String key) {
+		return redisTemplate.getExpire(key, TimeUnit.SECONDS);
+	}
+
+}

+ 67 - 0
src/main/java/com/caimei365/tools/task/StatisticsTask.java

@@ -0,0 +1,67 @@
+package com.caimei365.tools.task;
+
+import com.caimei365.tools.mapper.BaseMapper;
+import com.caimei365.tools.service.RedisService;
+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;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Map;
+
+/**
+ * Description
+ *
+ * @author : Charles
+ * @date : 2021/12/29
+ */
+@Slf4j
+@Configuration
+@EnableScheduling
+@RequiredArgsConstructor
+public class StatisticsTask {
+    @Resource
+    private BaseMapper baseMapper;
+    @Resource
+    private RedisService redisService;
+    /**
+     * 每天凌晨3点执行一次统计前一天商品访问量
+     * <p>
+     * cron表达式语法:秒 分 小时 日 月 周
+     * 年可省略
+     * * 表示所有值。
+     * ? 表示不指定值。
+     */
+    @Scheduled(cron = "0 0 3 * * ?")
+    public void countProductViews() {
+        try {
+            // 获取昨天日期字符串
+            Calendar calendar = Calendar.getInstance();
+            calendar.setTime(new Date());
+            calendar.add(Calendar.DAY_OF_MONTH, -1);
+            Date countTime = calendar.getTime();
+            String dateStr = new SimpleDateFormat("yyyyMMdd").format(countTime);
+            log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>【自动】统计前一天商品详情访问量,统计日期(前一天):" + dateStr);
+            // 获取Redis的Key: @Statistics(prefix = "statistics_details", field = "productId")
+            String redisKey = "statistics_details:productId:" + dateStr;
+            Map<Object, Object> result = redisService.hgetall(redisKey);
+            for (Map.Entry<Object, Object> entry : result.entrySet()) {
+                if (null != entry) {
+                    Integer productId = (Integer) entry.getKey();
+                    Integer views = (Integer) entry.getValue();
+                    if (null != productId) {
+                        baseMapper.insertProductViews(productId, views, countTime);
+                    }
+                }
+            }
+        } catch (Exception e) {
+            log.error("try-catch:",e);
+            log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>统计前一天商品详情访问量失败");
+        }
+    }
+}

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

@@ -90,6 +90,10 @@
         INSERT INTO cm_short_link (markId, shortLink, jumpLink, createTime)
         VALUES (#{markId}, #{shortLink}, #{url},NOW())
     </insert>
+    <insert id="insertProductViews">
+        INSERT INTO cm_product_views_record (productId, views, countTime)
+        VALUES (#{productId}, #{views}, #{countTime})
+    </insert>
     <update id="updateSmsSendCount">
         UPDATE cm_sms_statistics SET sendNum = (sendNum + #{count}) WHERE markId = #{markId}
     </update>