17.发布动态

发布动态

一、MovementsController

package com.tanhua.server.controller;

import com.tanhua.model.mongo.Movement;
import com.tanhua.server.service.MovementsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 圈子
 */
@RestController
@RequestMapping("/movements")
public class MovementsController {



    @Autowired
    private MovementsService movementsService;


    /**
     * 发布动态:
     * 请求路径:/movements
     * 请求方式:post
     * 请求参数:动态图片imageContent,还有Movenment
     * 响应数据:null
     */

    @PostMapping
    public ResponseEntity publishMoments(Movement movement, MultipartFile[] imageContent) throws IOException {

        //1.接收参数,调用api完成动态发布
        movementsService.publishMoments(movement,imageContent);
        //2.响应数据

        return ResponseEntity.ok(null);
    }



}

二、MovementsService

package com.tanhua.server.service;

import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.MovementsApi;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.ThreadLocalUntils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class MovementsService {


    @DubboReference
    private MovementsApi movementsApi;

    @Autowired
    private OssTemplate ossTemplate;

    //发布动态
    public void publishMoments(Movement movement, MultipartFile[] imageContent) throws IOException {

        //1.判断用户发布的动态的文字内容是否为空,为空则抛出异常
        if(StringUtils.isEmpty(movement.getTextContent())){
            throw new BusinessException(ErrorResult.contentError());
        }

        //2.获取当前登录的用户id
        Long userId = ThreadLocalUntils.getUserId();

        //3.遍历发布的图片数组,上传到阿里云oss,得到图片访问路径

        List<String> urls = new ArrayList<>();
        for (MultipartFile multipartFile : imageContent) {
            String imageUrl = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
            urls.add(imageUrl);
        }

        //4.把用户id和图片的访问路径集合封装进动态详情对象
        movement.setUserId(userId);
        movement.setMedias(urls);

        //5.调用api完成发布动态
        movementsApi.publishMoments(movement);

    }
}

三、MovementsApiImpl

package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class MovementsApiImpl implements MovementsApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Autowired
    private IdWorker idWorker;
    /**
     *发布动态
     */
    public void publishMoments(Movement movement) {

        //1.保存用户发布的动态到动态详情表,保存之间先封装齐movement数据
        // 先设置pid,再设置发布时间
        movement.setPid(idWorker.getNextId("movement"));
        movement.setCreated(System.currentTimeMillis());
        mongoTemplate.save(movement);

        //2.根据当前登录用户的id查询好友
        Criteria criteria = Criteria.where("userId").is(movement.getUserId());
        Query query = Query.query(criteria);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);

        //3.遍历好友集合,为每个好友设置时间线
        for (Friend friend : friends) {
            MovementTimeLine mtl = new MovementTimeLine();
            mtl.setMovementId(movement.getId());
            mtl.setUserId(friend.getUserId());
            mtl.setFriendId(friend.getFriendId());
            mtl.setCreated(System.currentTimeMillis());
        }


    }
}

四、代码优化

1.启动类上添加@@EnableAsync注解

2.新建一个类,异步处理工具类,SaveTimeLIne;

把它注入为spring管理的bean,在方法上使用@Async注解,把查询好友跟添加好友时间线的代码抽取出来

package com.tanhua.dubbo.utils;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.MovementTimeLine;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SaveTimeLIne {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Async
    public void saveTimeLine(Long userId, ObjectId movementId){


        //2.根据当前登录用户的id查询好友
        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 mtl = new MovementTimeLine();
            mtl.setMovementId(movementId);
            mtl.setUserId(friend.getUserId());
            mtl.setFriendId(friend.getFriendId());
            mtl.setCreated(System.currentTimeMillis());
        }

    }
}

三、api实现类上直接调用方法

package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.SaveTimeLIne;
import com.tanhua.model.mongo.Movement;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;

@DubboService
public class MovementsApiImpl implements MovementsApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Autowired
    private IdWorker idWorker;



    @Autowired
    private SaveTimeLIne saveTimeLIne;


    /**
     *发布动态
     */
    public void publishMoments(Movement movement) {

        //1.保存用户发布的动态到动态详情表,保存之间先封装齐movement数据
        // 先设置pid,再设置发布时间
        movement.setPid(idWorker.getNextId("movement"));
        movement.setCreated(System.currentTimeMillis());
        mongoTemplate.save(movement);

        saveTimeLIne.saveTimeLine(movement.getUserId(), movement.getId());

    }
}


posted @ 2022-10-30 12:09  给我手牵你走  阅读(49)  评论(0编辑  收藏  举报