我想在以下 springboot 应用程序中每 3 秒向 http://localhost:8080/markable/messages 请求一次 post

I want to do post request every 3 seconds to http://localhost:8080/markable/messages in the following springboot application

这些是我开发的文件,但是我仍然无法实现上面所说的post。请告诉我我要去哪里 wrong.My 代码在 postman 和 springboot tomcat 上运行良好,但是我想将 post 自动化到 /messages url。

MessageController.java

import java.util.HashSet;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import service.MessageService;
import model.Message;

@RestController
@RequestMapping("/markable")
public class MessageController {

    @Autowired 
    MessageService ms;

    @RequestMapping(value="/messages", method=RequestMethod.POST)
    public HttpStatus takeInput(@RequestBody Message input) {
        boolean flag=ms.addMissionId(input.getMissionId());
        System.out.println(flag);

        if(flag)
            return HttpStatus.CREATED;
        else 
            return HttpStatus.CONFLICT;
    }

    @RequestMapping("/messages/all")
    public HashSet<Integer> getAll() {
        return ms.getAll();
    }

    @RequestMapping("/messages/{id}")
    public int getMissionId(@PathVariable("id") String id)
    {
        int inputId = Integer.parseInt(id);
        return ms.getMissionId(inputId);
    }
}

FixedMessagePoster.java

package poster;
import model.Message;
import org.apache.commons.logging.Log;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

@Component
public class FixedRateMessagePoster {

    Message m;
    int count=0;

    @Scheduled(fixedRate=3000)
    public void doPost()
    {
        try {
            m=new Message();
            m.setMissionId(count);
            count++;
            int seed = 1000+(int)(Math.random()*(20000-1000) +1);
            m.setSeed(seed);

            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
            restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
            String uri = new String("http://localhost:8080/markable/messages");

            restTemplate.postForLocation(uri,m);

            System.out.println("hello");
        } catch (HttpClientErrorException e) {
            e.printStackTrace();
        }
        catch(Exception e) {
           e.printStackTrace();
        }
    }
}

MessageService.java

package service;

import java.util.HashSet;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import model.Message;
import controller.MessageController;

@Service
public class MessageService {

    static HashSet<Integer> missionIds = new HashSet<Integer>();

    public HashSet<Integer> getAll(){
        return missionIds;
    }

    public boolean addMissionId(int missionId) {
        return missionIds.add(missionId);
    }

    public int getMissionId(int id){
        if(missionIds.contains(id))
            return id;
        else 
            return -1;
    }
}

POM.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>Markable</name>
    <description>Spring Boot Application for Markable</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.spring.framework</groupId>
            <artifactId>gs-scheduling-tasks</artifactId>
            <version>0.1.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

有些东西看起来很奇怪。

  1. 为什么要在 spring 上导入一些入门项目?这根本没有意义。
  2. 由于您的问题缺少您的应用程序 class,请仔细检查您是否添加了 @EnableScheduling 注释。
  3. 为什么要通过 RestTemplate 在自己的应用程序中调用休息控制器?本质上,您可以直接在 FixedMessagePoster 中注入消息服务,并每隔 x 秒添加一次这些调用。
  4. 如果您将 RestTemplate 创建为 bean(@Bean 在您的应用程序或配置 class 中),则不必添加所有 MessageConverter 每次调用。
  5. 在 if-else 周围添加大括号确实是一个很好的做法,即使您可以离开 then away。这将增加可读性。
  6. 在某些 classes 中,您正在导入 Message 而它却无处使用。
  7. 由于您在 FixedMessagePoster 中发布的消息仅在本地方法中使用,我强烈建议您将此方法也设为本地方法,而不是 class 的成员。
  8. 你不应该使用 System.out 来输出一些信息。只需使用 Spring Boot 中内置的记录器。 (提示:slf4j,你不会依赖于所使用的框架)
  9. 你的异常处理不理想。只将真正需要的内容包装到 try-catch 中。