SpringBoot注解创建多线程 + 基于List实现分页

一、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());            
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值