赞
踩
在互联网应用中经常会有积分的概念,会员积分是一种成长手段,就像游戏中的等级一样,通过积分叠加,让用户深刻感受到自己的价值在提升。
积分的诞生远早于互联网产品,积分从本质上讲是衡量用户消费或贡献行为的标尺,是维护忠诚度的一个重要手段。
积分获取的设计主要包括两部分:一是确定哪些行为可以获取积分;二是确定积分兑换比例。
以增长黑客模型(AARRR)作为目标基础,奖励的行为可以一般分为四个维度:打开、活跃、消费、传播。
企业一直以来的发展方式,大都离不开推陈出新、吸引新客户、拓展销售渠道,而随着企业地不断发展,企业往往会面临新品推广困难、拉新乏力、客户不活跃、复购率低等难以解决的痛点。而搭建积分商城,却可以帮助企业解决这些问题。
企业可以设置多种积分获取途径,增加客户手上的积分数量,并在积分商城平台上设置多种不同类型的积分兑换方式,吸引新客户持续访问,并以新用户专享福利等方式,刺激用户完成首单转化(目的),拉动复购
对那些活跃度不高的老客户,可以采取积分赠送、签到送积分、发放优惠券等形式来进行唤醒,达到再次消费的目的。积分助力产生会员等级,等级为顾客带来不同权益,同时可以给消费者带来荣誉感和尊享感,满足消费者心理需求;
企业可以借助积分这种载体,来强化客户权益,来让忠实的客户享受到一定的高折扣优惠以及积分兑换权益,对提升客户留存非常有帮助。
本文主要讲解一下两个功能设计与实现:
CREATE TABLE `t_user_points` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fk_user_id` int(11) DEFAULT NULL COMMENT '用户id',
`points` int(11) DEFAULT NULL COMMENT '积分',
`types` int(11) DEFAULT NULL COMMENT '积分类型:0=签到,1=关注好友,2=添加评论,3=点赞商户',
`is_valid` int(11) DEFAULT NULL COMMENT '是否有效 1=有效,0=无效',
`create_date` datetime DEFAULT NULL COMMENT '创建时间',
`update_date` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=COMPACT;
pom文件引入相关依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>redis-seckill</artifactId>
<groupId>com.zjq</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ms-points</artifactId>
<dependencies>
<!-- eureka client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- spring web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- spring data redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<!-- commons 公共项目 -->
<dependency>
<groupId>com.zjq</groupId>
<artifactId>commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- test 单元测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
yml配置文件:
server:
port: 7006 # 端口
spring:
application:
name: ms-points # 应用名
# 数据库
# 数据库
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://127.0.0.1:3306/seckill?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false
# Redis
redis:
port: 6379
host: localhost
timeout: 3000
password: 123456
database: 2
# Swagger
swagger:
base-package: com.zjq.points
title: 积分功能微服务API接口文档
# 配置 Eureka Server 注册中心
eureka:
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
client:
service-url:
defaultZone: http://localhost:7000/eureka/
service:
name:
ms-oauth-server: http://ms-oauth2-server/
ms-users-server: http://ms-users/
mybatis:
configuration:
map-underscore-to-camel-case: true # 开启驼峰映射
logging:
pattern:
console: '%d{HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n'
REST请求配置类和Redis配置类和全局异常处理:
RestTemplate 配置类:
package com.zjq.points.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.util.Collections;
/**
* RestTemplate 配置类
* @author zjq
*
*/
@Configuration
public class RestTemplateConfiguration {
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_PLAIN));
restTemplate.getMessageConverters().add(converter);
return restTemplate;
}
}
RedisTemplate配置类:
package com.zjq.points.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* RedisTemplate配置类
*
* @author zjq
*/
@Configuration
public class RedisTemplateConfiguration {
/**
* redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类
*
* @param redisConnectionFactory
* @return
*/
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 使用Jackson2JsonRedisSerialize 替换默认序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
// 设置key和value的序列化规则
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
/**
* 用户积分实体
* @author zjq
*/
@Getter
@Setter
public class UserPoints extends BaseModel {
@ApiModelProperty("关联userId")
private Integer fkUserId;
@ApiModelProperty("积分")
private Integer points;
@ApiModelProperty(name = "类型",example = "0=签到,1=关注好友,2=添加Feed,3=添加商户评论")
private Integer types;
}
/**
* 添加积分
*
* @param userId 用户ID
* @param points 积分
* @param types 类型 0=签到,1=关注好友,2=添加Feed,3=添加商户评论
* @return
*/
@PostMapping
public ResultInfo<Integer> addPoints(@RequestParam(required = false) Integer userId,
@RequestParam(required = false) Integer points,
@RequestParam(required = false) Integer types) {
userPointsService.addPoints(userId, points, types);
return ResultInfoUtil.buildSuccess(request.getServletPath(), points);
}
/**
* 添加积分
*
* @param userId 用户ID
* @param points 积分
* @param types 类型 0=签到,1=关注好友,2=添加Feed,3=添加商户评论
*/
@Transactional(rollbackFor = Exception.class)
public void addPoints(Integer userId, Integer points, Integer types) {
// 基本参数校验
AssertUtil.isTrue(userId == null || userId < 1, "用户不能为空");
AssertUtil.isTrue(points == null || points < 1, "积分不能为空");
AssertUtil.isTrue(types == null, "请选择对应的积分类型");
// 插入数据库
UserPoints userPoints = new UserPoints();
userPoints.setFkUserId(userId);
userPoints.setPoints(points);
userPoints.setTypes(types);
userPointsMapper.save(userPoints);
}
/**
* 添加积分
* @param userPoints 用户积分实体
*/
@Insert("insert into t_user_points (fk_user_id, points, types, is_valid, create_date, update_date) " +
" values (#{fkUserId}, #{points}, #{types}, 1, now(), now())")
void save(UserPoints userPoints);
spring:
application:
name: ms-gateway
cloud:
gateway:
discovery:
locator:
enabled: true # 开启配置注册中心进行路由功能
lower-case-service-id: true # 将服务名称转小写
routes:
# 积分服务路由
- id: ms-points
uri: lb://ms-points
predicates:
- Path=/points/**
filters:
- StripPrefix=1
在用户服务中添加 ms-points 服务的地址:
service:
name:
# oauth2 服务地址
ms-oauth-server: http://ms-oauth2-server/
# 积分服务地址
ms-points-server: http://ms-points/
积分类型枚举 :
/**
* 积分类型
* @author zjq
*/
@Getter
public enum PointTypesConstant {
sign(0),
follow(1),
feed(2),
review(3)
;
private int type;
PointTypesConstant(int key) {
this.type = key;
}
}
签到业务逻辑层调整,增加签到后积分变动:
/**
* 添加用户积分
*
* @param count 连续签到次数
* @param signInUserId 登录用户id
* @return 获取的积分
*/
private int addPoints(int count, Integer signInUserId) {
// 签到1天送10积分,连续签到2天送20积分,3天送30积分,4天以上均送50积分
int points = 10;
if (count == 2) {
points = 20;
} else if (count == 3) {
points = 30;
} else if (count >= 4) {
points = 50;
}
// 调用积分接口添加积分
// 构建请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 构建请求体(请求参数)
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("userId", signInUserId);
body.add("points", points);
body.add("types", PointTypesConstant.sign.getType());
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body, headers);
// 发送请求
ResponseEntity<ResultInfo> result = restTemplate.postForEntity(pointsServerName,
entity, ResultInfo.class);
AssertUtil.isTrue(result.getStatusCode() != HttpStatus.OK, "登录失败!");
ResultInfo resultInfo = result.getBody();
if (resultInfo.getCode() != ApiConstant.SUCCESS_CODE) {
// 失败了, 事物要进行回滚
throw new ParameterException(resultInfo.getCode(), resultInfo.getMessage());
}
return points;
}
id为6的用户发起签到:
查看数据库和redis可以发现用户积分已经增加:
通过如下方法,初始化两万条积分和用户记录:
// 初始化 2W 条积分记录
@Test
void addPoints() throws Exception {
List<Map<Integer, Integer[]>> dinerInfos = Lists.newArrayList();
for (int i = 1; i <= 2000; i++) {
for (int j = 0; j < 10; j++) {
super.mockMvc.perform(MockMvcRequestBuilders.post("/")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("userId", i + "")
.param("points", RandomUtil.randomNumbers(2))
.param("types", "0")
).andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
}
}
}
其实这个类似于一张日志表,因此数据量是非常庞大的,当我们想要统计用户积分做排行榜的的时候,比如:获取积分排行榜Top20,显示字段有:用户id、用户昵称、头像、总积分以及排行榜
获取积分排行榜TOP20:
SELECT
t1.fk_user_id AS id,
sum( t1.points ) AS total,
rank() over (ORDER BY sum( t1.points ) DESC) AS ranks,
t2.nickname,
t2.avatar_url
FROM
t_user_points t1
LEFT JOIN t_users t2 ON t1.fk_user_id = t2.id
WHERE
t1.is_valid = 1
AND t2.is_valid = 1
GROUP BY
t1.fk_user_id
ORDER BY
total DESC
LIMIT 20
获取当前登录用户的排行情况:
SELECT id, total, ranks, nickname, avatar_url FROM (
SELECT t1.fk_user_id AS id,
sum( t1.points ) AS total,
rank () over ( ORDER BY sum( t1.points ) DESC ) AS ranks,
t2.nickname, t2.avatar_url
FROM t_user_points t1 LEFT JOIN t_users t2 ON t1.fk_user_id = t2.id
WHERE t1.is_valid = 1 AND t2.is_valid = 1
GROUP BY t1.fk_user_id
ORDER BY total DESC ) r
WHERE id = '6';
这种方式看上去比较简单,如果数据量小的话运行应该也没有什么大问题,但如果当数据量超过一定量以后,就会出现很大的延迟,毕竟MySQL查询是要消耗大量的IO的。我们后面可以测试一下。
/**
* 用户积分总排行榜
* @author zjq
*/
@ApiModel(description = "用户积分总排行榜")
@Getter
@Setter
public class UserPointsRankVO extends ShortUserInfo {
@ApiModelProperty("总积分")
private Integer total;
@ApiModelProperty("排名")
private Integer ranks;
@ApiModelProperty(value = "是否是自己", example = "0=否,1=是")
private Integer isMe;
}
/**
* 查询前 20 积分排行榜,同时显示用户排名 -- MySQL
*
* @param access_token
* @return
*/
@GetMapping
public ResultInfo findDinerPointsRank(String access_token) {
List<UserPointsRankVO> ranks = userPointsService.findDinerPointRank(access_token);
return ResultInfoUtil.buildSuccess(request.getServletPath(), ranks);
}
/**
* 查询前 20 积分排行榜,并显示个人排名 -- MySQL
*
* @param accessToken
* @return
*/
public List<UserPointsRankVO> findDinerPointRank(String accessToken) {
// 获取登录用户信息
SignInUserInfo SignInUserInfo = loadSignInUserInfo(accessToken);
// 统计积分排行榜
List<UserPointsRankVO> ranks = userPointsMapper.findTopN(TOPN);
if (ranks == null || ranks.isEmpty()) {
return Lists.newArrayList();
}
// 根据 key:用户 ID value:积分信息 构建一个 Map
Map<Integer, UserPointsRankVO> ranksMap = new LinkedHashMap<>();
for (int i = 0; i < ranks.size(); i++) {
ranksMap.put(ranks.get(i).getId(), ranks.get(i));
}
// 判断个人是否在 ranks 中,如果在,添加标记直接返回
if (ranksMap.containsKey(SignInUserInfo.getId())) {
UserPointsRankVO myRank = ranksMap.get(SignInUserInfo.getId());
myRank.setIsMe(1);
return Lists.newArrayList(ranksMap.values());
}
// 如果不在 ranks 中,获取个人排名追加在最后
UserPointsRankVO myRank = userPointsMapper.findUserRank(SignInUserInfo.getId());
myRank.setIsMe(1);
ranks.add(myRank);
return ranks;
}
/**
* 查询积分排行榜 TOPN
* @param top 前多少名
* @return 排行榜集合
*/
@Select("SELECT t1.fk_user_id AS id, " +
" sum( t1.points ) AS total, " +
" rank () over ( ORDER BY sum( t1.points ) DESC ) AS ranks," +
" t2.nickname, t2.avatar_url " +
" FROM t_user_points t1 LEFT JOIN t_users t2 ON t1.fk_user_id = t2.id " +
" WHERE t1.is_valid = 1 AND t2.is_valid = 1 " +
" GROUP BY t1.fk_user_id " +
" ORDER BY total DESC LIMIT #{top}")
List<UserPointsRankVO> findTopN(@Param("top") int top);
/**
* 根据用户 ID 查询当前用户的积分排名
* @param userId 用户id
* @return 用户积分实体
*/
@Select("SELECT id, total, ranks, nickname, avatar_url FROM (" +
" SELECT t1.fk_user_id AS id, " +
" sum( t1.points ) AS total, " +
" rank () over ( ORDER BY sum( t1.points ) DESC ) AS ranks," +
" t2.nickname, t2.avatar_url " +
" FROM t_user_points t1 LEFT JOIN t_users t2 ON t1.fk_user_id = t2.id " +
" WHERE t1.is_valid = 1 AND t2.is_valid = 1 " +
" GROUP BY t1.fk_user_id " +
" ORDER BY total DESC ) r " +
" WHERE id = #{userId}")
UserPointsRankVO findUserRank(@Param("userId") int userId);
因为t_user_points
本质上是一张日志表,记录了所有用户的积分记录,因此直接去数据库统计的话会有如下问题:
下篇博客我将讲解如何通过Redis来实现积分排行榜,提高并发性能和吞吐量。
本文内容到此结束了,
如有收获欢迎点赞声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/152876?site
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。