feat: 稍微修改一下

master
flying_pig 1 month ago
parent a149712420
commit 8128f76a4e

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="17" project-jdk-type="JavaSDK" />
</project>

@ -1,5 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoImportSettings">
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="b4c20391-644c-4ef8-93ae-166260c047e0" name="更改" comment="" />
<option name="SHOW_DIALOG" value="false" />
@ -17,6 +20,11 @@
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"WebServerToolWindowFactoryState": "false",
"node.js.detected.package.eslint": "true",
"node.js.detected.package.tslint": "true",
"node.js.selected.package.eslint": "(autodetect)",
"node.js.selected.package.tslint": "(autodetect)",
"nodejs_package_manager_path": "npm",
"vue.rearranger.settings.migration": "true"
}
}]]></component>
@ -29,7 +37,11 @@
<option name="presentableId" value="Default" />
<updated>1727955603618</updated>
<workItem from="1727955604708" duration="5000" />
<workItem from="1728893452698" duration="322000" />
</task>
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="3" />
</component>
</project>

@ -21,7 +21,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.8.0</version> <!-- 选择合适的版本 -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>

@ -0,0 +1,29 @@
package com.flyingpig.kclassrollcall.init;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.sql.DataSource;
@Slf4j(topic = "Initialize")
@RestController
@RequiredArgsConstructor
public class InitializeController {
private final DataSource dataSource;
@GetMapping("/initialize/application")
public void initializeDispatcherServletAndDataSource() {
log.info("开始初始化DispatcherServlet和数据源");
try {
log.info("初始化DispatcherServlet和数据源成功");
dataSource.getConnection().createStatement().execute("SELECT 1");
} catch (Exception e) {
log.error("初始化DispatcherServlet和数据源失败", e);
}
}
}

@ -1,17 +0,0 @@
package com.flyingpig.kclassrollcall.init;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j(topic = "Initialize DispatcherServlet")
@RestController
public final class InitializeDispatcherServletController {
@GetMapping("/initialize/dispatcher-servlet")
public void initializeDispatcherServlet() {
log.info("Initialized the dispatcherServlet to improve the first response time of the interface...");
}
}

@ -52,48 +52,32 @@ public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> impl
if (!mode.equals(RollCallMode.EQUAL)) {
return Result.success(rollBackStudentBaseScore());
} else {
return Result.success(selectStudentByTeacherId().get(new Random().nextInt(count()) - 1));
List<Student> students = this.baseMapper.selectList(new LambdaQueryWrapper<Student>()
.eq(Student::getTeacherId, UserContext.getUser()));
return Result.success(students.get(new Random().nextInt(students.size())));
}
}
private List<Student> selectStudentByTeacherId() {
List<StudentInfoInCache> cachedList = listCacheUtil.safeGetWithLock(
RedisConstant.STUDENT_LIST_KEY + UserContext.getUser(),
StudentInfoInCache.class, // 使用具体的 StudentInfoInCache.class 作为类型
return listCacheUtil.safeGetWithLock(
RedisConstant.STUDENT_LIST_KEY + UserContext.getUser(), // Redis Key
Student.class,
() -> {
// 查询学生的逻辑,转换为 StudentInfoInCache 列表
// 查询学生ID的逻辑
return this.baseMapper.selectList(new LambdaQueryWrapper<Student>()
.eq(Student::getTeacherId, UserContext.getUser())).stream()
.map(student -> new StudentInfoInCache(student.getId(), student.getName(), student.getNo(), student.getMajor()))
.collect(Collectors.toList());
.eq(Student::getTeacherId, UserContext.getUser()));
},
30L,
30L, // 缓存时间
TimeUnit.MINUTES
);
List<Student> students = new ArrayList<>();
for (StudentInfoInCache studentInfo : cachedList) {
Student newStudent = new Student();
BeanUtil.copyProperties(studentInfo, newStudent);
newStudent.setScore(stringCacheUtil.safeGetWithLock(
RedisConstant.STUDENT_SCORE_KEY + studentInfo.getId(),
Double.class, // 传入正确的类型
() -> {
return this.getBaseMapper().selectById(studentInfo.getId()).getScore();
},
30L,
TimeUnit.MINUTES
));
newStudent.setTeacherId(Long.parseLong(UserContext.getUser()));
students.add(newStudent);
}
return students;
}
private Student rollBackStudentBaseScore() {
// 获取符合条件的学生列表
List<Student> students = selectStudentByTeacherId();
List<Student> students = this.baseMapper.selectList(new LambdaQueryWrapper<Student>()
.eq(Student::getTeacherId, UserContext.getUser()));
// 计算权重
double totalWeight = 0;
Map<Student, Double> weightMap = new HashMap<>();

@ -11,6 +11,7 @@ import com.flyingpig.kclassrollcall.service.ITeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.flyingpig.kclassrollcall.util.JwtUtil;
import org.apache.catalina.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
/**
@ -28,11 +29,10 @@ public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> impl
@Override
public Result login(LoginReq loginReq) {
Teacher teacher = this.getOne(new LambdaQueryWrapper<Teacher>()
.eq(Teacher::getUsername, loginReq.getUsername())
.eq(Teacher::getPassword, loginReq.getPassword()));
if(teacher == null){
.eq(Teacher::getUsername, loginReq.getUsername()));
if (teacher == null || !new BCryptPasswordEncoder().matches(loginReq.getPassword(), teacher.getPassword())) {
return Result.error("账号或密码错误");
}else {
} else {
return Result.success(new LoginResp(teacher.getName(), JwtUtil.createJWT(teacher.getId().toString())));
}
}
@ -40,9 +40,9 @@ public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> impl
@Override
public Result register(Teacher teacher) {
try {
save(teacher);
save(teacher.setPassword(new BCryptPasswordEncoder().encode(teacher.getPassword())));
return Result.success("注册成功");
}catch (Exception e){
} catch (Exception e) {
log.error(e.getMessage());
return Result.error("注册失败,可能存在用户名已被注册等问题");
}

@ -1,72 +0,0 @@
package com.flyingpig.kclassrollcall;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flyingpig.kclassrollcall.common.RedisConstant;
import com.flyingpig.kclassrollcall.common.Result;
import com.flyingpig.kclassrollcall.common.RollCallMode;
import com.flyingpig.kclassrollcall.dto.resp.StudentInfoInCache;
import com.flyingpig.kclassrollcall.entity.Student;
import com.flyingpig.kclassrollcall.filter.UserContext;
import com.flyingpig.kclassrollcall.mapper.StudentMapper;
import com.flyingpig.kclassrollcall.service.impl.StudentServiceImpl;
import com.flyingpig.kclassrollcall.util.cache.ListCacheUtil;
import com.flyingpig.kclassrollcall.util.cache.StringCacheUtil;
import com.google.common.cache.CacheLoader;
import org.apache.poi.ss.formula.functions.T;
import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.*;
import static org.mockito.ArgumentMatchers.any;
@ExtendWith(MockitoExtension.class)
public class StudentServiceImplTest {
@Mock
private StudentMapper studentMapper;
@Mock
private ListCacheUtil listCacheUtil;
@Mock
private StringCacheUtil stringCacheUtil;
@InjectMocks
private StudentServiceImpl studentService;
@Test
public <T>
void testRollCall() {
// 模拟依赖方法
// 调用依赖方法方法
Mockito.doReturn(Result.success()).when(studentService).rollCall(RollCallMode.EQUAL);
List<Student> mockStudents = Arrays.asList(
new Student(1L, "Alice", 1, "Math", 50.0, 100L),
new Student(2L, "Bob", 2, "Science", 0.0, 100L)
);
when(studentMapper.selectList(new LambdaQueryWrapper<Student>().eq(Student::getTeacherId, any()))).thenReturn(mockStudents);
// 模拟 rollCall 调用
Result result = studentService.rollCall(RollCallMode.EQUAL);
// 验证返回结果
assertNotNull(result);
assertTrue(mockStudents.contains(result.getData())); // 随机选择一个学生
}
}

@ -1,11 +1,11 @@
{
"name": "k-class-roll-call",
"name": "k-calss-rall-call",
"version": "0.1.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "k-class-roll-call",
"name": "k-calss-rall-call",
"version": "0.1.0",
"dependencies": {
"axios": "^1.5.1",

Loading…
Cancel
Save