一、SpringBoot注解创建多线程
多线程有利于提高代码运行效率,减少用户的等待响应的时间以及规避掉因为响应时间过久服务宕机的问题。SpringBoot提供了两个注解 @EnableAsync 和 @Async简化多线程的操作。
具体实现步骤:
(1)启动类上添加@EnableAsync ---开启异步处理支持
@Slf4j
@SpringBootApplication
@EnableAsync //开启异步处理的支持
public class DubboMongoApplication {
public static void main(String[] args) {
SpringApplication.run(DubboMongoApplication.class, args);
log.info("dubbo-mongo 服务启动");
}
}
(2)在需要开启多线程的方法上添加@Async----开启多线程;注意,如果是添加在类上,意味着整个类里的方法都是异步操作的
@Component
public class TimeLineService {
@Autowired
private MongoTemplate mongoTemplate;
@Async//底层使用多线程实现
public void saveTimeLine(Long userId, ObjectId movementId) {
//2.查询当前用户的好友数据
Criteria criteria = Criteria.where("userId").is(userId);
Query query = Query.query(criteria);
List<Friend> friends = mongoTemplate.find(query, Friend.class);
//3.循环好友数据,构建时间线数据存入数据库中
for (Friend friend : friends) {
MovementTimeLine timeLine = new MovementTimeLine();
timeLine.setMovementId(movementId);
timeLine.setUserId(friend.getUserId());
timeLine.setFriendId(friend.getFriendId());
timeLine.setCreated(System.currentTimeMillis());
mongoTemplate.save(timeLine);
}
}
}
二、基于List实现分页
实现思路:基于Steam流处理,配和skip()和limit()两个方法模拟分页效果,skip( )---开始的下标;limit( )---一次读取的数据量
//10020,28,10092,24,25,27,10064,26,10067,20,16,10099,19,10015,10040,10093,18,17,22,10081
String[] valueArr = redisValue.split(",");
//判断当前页的起始条数是否小于数组的长度(防止数组的空指针异常)
if((page - 1 )*pageSize < valueArr.length){
List<Long> pids = Arrays.stream(valueArr)
.skip((page - 1) * pageSize).limit(pageSize)
.collect(Collectors.toList());
}