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

时间:2016-06-26 08:05:54

标签: spring-boot scheduled-tasks

这些是我开发的文件,但是我仍然无法实现上述帖子。请告诉我我哪里出错了。我的代码与postman和springboot tomcat一起工作正常,但是我想将帖子自动化到/ 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 个答案:

答案 0 :(得分:0)

有些事情看起来很奇怪。

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