网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
<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>
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:
s
p
r
i
n
g
.
c
l
o
u
d
.
c
l
i
e
n
t
.
i
p
−
a
d
d
r
e
s
s
:
{spring.cloud.client.ip-address}:
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 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);
}
#### 数据交互mapper层
/\*\*
* 添加积分
* @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);
#### 网关 ms-gateway 服务添加积分微服务路由
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 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可以发现用户积分已经增加:


### 积分排行榜TopN(关系型数据库)
* 读取数据库中积分,排行榜取TopN,显示字段有:用户id、用户昵称、头像、总积分以及排行榜
* 需要标记当前登录用户的排行情况
#### 构造数据
通过如下方法,初始化两万条积分和用户记录:
// 初始化 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的。我们后面可以测试一下。
#### 用户积分排名对象



**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!**
**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**
**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.youkuaiyun.com/forums/4f45ff00ff254613a03fab5e56a57acb)**
HERE id = '6';
这种方式看上去比较简单,如果数据量小的话运行应该也没有什么大问题,但如果当数据量超过一定量以后,就会出现很大的延迟,毕竟MySQL查询是要消耗大量的IO的。我们后面可以测试一下。
用户积分排名对象
[外链图片转存中…(img-ZrGXJMR0-1715480870381)]
[外链图片转存中…(img-IHEhATN6-1715480870382)]
[外链图片转存中…(img-St5T6bZG-1715480870382)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!
由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新