Springboot ActiveMQ Integrated Use

Source: Internet
Author: User
Tags spring initializr
Install ActiveMQ (see previous article)


Integrate

Idea to create a springboot project,

1. Open idea, create new project, select Spring INITIALIZR

2. Input artifact

3. Tick the Web

4. Click Finish

5. Enter the project, you can delete the following content

Because Springboot already has built-in support for ActiveMQ, it's a direct introduction to the spring-boot-starter-activemq of dependency. The overall project structure is as follows:

1,pom.xml documents

<?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.yuezhong</groupid> <artifactId>activemq</artifactId> <version>0.0.1-snapshot</ version> <packaging>jar</packaging> <name>activemq</name> <description>demo Project for Spring Boot activemq</description> <parent> <groupid>org.springframework.boot</ Groupid> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.release</ version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8< /project.build.sourceencoding> <project.reporting.outputencoding>utf-8</project.reporting.outputencoding> <java.version>1.8</java.version> </properties> <dependencies> <depen Dency> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starter-web</ artifactid> </dependency> <dependency> <groupId>org.springframework.boot</groupId> &

		Lt;artifactid>spring-boot-starter-test</artifactid> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId> spring-boot-starter-activemq</artifactid> </dependency> </dependencies> <build> <plugin s> <plugin> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-mave
 n-plugin</artifactid> </plugin> </plugins> </build> </project>
2, configuration fileApplication.properties
spring.activemq.broker-url=tcp://127.0.0.1:61616 # The time to wait before considering the end #spring. Activemq.close-timeout=15s # Whether the default proxy URL should be in memory.
If an explicit proxy is specified, this value is ignored. Spring.activemq.in-memory=true # stops message delivery before rolling back the message.
This means that when this command is enabled, the message order is not preserved. Spring.activemq.non-blocking-redelivery=false # password Spring.activemq.password=admin # waits for the message to be sent the response time.
Set to 0 wait forever. Spring.activemq.send-timeout=0 Spring.activemq.user=admin # Whether to trust all packages #spring. activemq.packages.trust-all= # A comma-delimited list of specific packages to be trusted (when all packages are not trusted) #spring. activemq.packages.trusted= # When connection requests and China are blocked.
Setting false throws "JMSException exception".
#spring. Activemq.pool.block-if-full=true # If the pool is still full, block the time before throwing an exception. #spring. activemq.pool.block-if-full-timeout=-1ms # Whether to create a connection at startup.
Can be used for heating pools at startup.
#spring. Activemq.pool.create-connection-on-startup=true # Use Pooledconnectionfactory instead of ordinary connectionfactory.
#spring. Activemq.pool.enabled=false # Connection Expiration timeout. #spring. ACTIVEMQ.POOL.EXPIRY-TIMEOUT=0MS # Connection idle timeout #spring. activemq.pool.idle-timeout=30s # Connection pool Maximum number of connections #
Spring.activemq.pool.max-connections=1 # Maximum number of valid sessions per connection. #spring. Activemq.pool.maximum-active-session-per-connection=500 # Try to reconnect #spring when there is "jmsexception". activemq.pool.reconnect-on-exception= True # The time to run between idle connections scavenging threads.
When negative, there is no idle connection to evict the thread from running. #spring. activemq.pool.time-between-expiration-check=-1ms # Whether to use only one MessageProducer # Spring.activemq.pool.use-anonymous-producers=true
3, Send Message Class
Package com.yuezhong.activemq.client;

Import Org.springframework.jms.annotation.JmsListener;
Import org.springframework.stereotype.Component;
Import Org.springframework.util.StringUtils;

/**
 * Created by Yz.shi on 2018/4/9.
 * *
@Component public
class Activemqclient {

    //use Jmslistener to configure the queue that the consumer listens to, where text is the received message
    @JmsListener (Destination = "Mytest.queue")
    public void Receivequeue (String text) {
        if (! Stringutils.isempty (text)) {
            System.out.println ("Activemqserver received message is:" +text);
            System.out.println ("");}}}

4. message Receiving Class

Package com.yuezhong.activemq.server;

Import Org.apache.activemq.command.ActiveMQQueue;
Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.jms.core.JmsTemplate;
Import org.springframework.scheduling.annotation.EnableScheduling;
Import org.springframework.scheduling.annotation.Scheduled;
Import org.springframework.stereotype.Component;
Import javax.jms.Destination;

/**
 * Created by Yz.shi on 2018/4/9.
 * *
@Component
@EnableScheduling public
class Activemqserver {

    @Autowired
    private Jmstemplate jmstemplate;

    static int index = 0;

    Destination Destination = new Activemqqueue ("Mytest.queue");

    @Scheduled (Fixeddelay = 5000)//5s Execute once   only the parameterless method can use this annotation public
    void SendMessage () {
        index++;
        String message = "Shiyuezhong" + index;
        This.jmsTemplate.convertAndSend (destination, message);
    }


5, Activemqapplication

Package Com.yuezhong;

Import Com.yuezhong.queue.producer.Producer;
Import Org.apache.activemq.command.ActiveMQQueue;
Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.boot.SpringApplication;
Import org.springframework.boot.autoconfigure.SpringBootApplication;
Import javax.annotation.PostConstruct;
Import javax.jms.Destination;

@SpringBootApplication public
class Activemqapplication {public
   
   static void Main (string[] args) {
        Springapplication.run (Activemqapplication.class, args);
    }



Another: Producer

Package com.yuezhong.queue.producer;
Import Org.apache.activemq.command.ActiveMQQueue;
Import Org.springframework.jms.core.JmsTemplate;
Import org.springframework.scheduling.annotation.Scheduled;
Import Org.springframework.stereotype.Service;
Import javax.jms.Destination;

Import Javax.annotation.Resource;
 /** * Created by Yz.shi on 2018/4/9.

    * * @Service ("producer") public class producer {@Resource private jmstemplate jmstemplate; /** * Send Message (Main method set Queue) * * @param destination sent to the queue * @param message to be sent/public void
    Convertandsend (destination destination, final String message) {jmstemplate.convertandsend (destination, message);
    /** * Send message (timed send queue) */static int i = 100;

    Destination Destination = new Activemqqueue ("Yzshi_queue");
        @Scheduled (Fixeddelay = 5000)//5s Execute once only the parameterless method can use this annotation public void Convertandsend () {i++; String message = "This is the first" + i + "messages sent by the timed task Queueproducer. ";
        Jmstemplate.convertandsend (destination, message);
 }

}
Consumerb
Package Com.yuezhong.queue.consumer;

Import Org.springframework.jms.annotation.JmsListener;
Import Org.springframework.messaging.handler.annotation.SendTo;
Import org.springframework.stereotype.Component;

/**
 * Created by Yz.shi on 2018/4/9.
 * *
@Component public
class Consumerb {
    /**
     * Use Jmslistener to configure consumer listening queues
     *
     * @param text received messages
     */
    @JmsListener (Destination = "Yzshi_queue")
    @SendTo ("Out.queue") public
    String Receivequeue ( String text) {
        System.out.println ("----------------consumer-b: The message Received is:" + text);
        return text;

    @JmsListener (Destination = "yzshi_queue") public
    void Printreceivequeue (String text) {
        System.out.println ( "+++++++++++++++++consumer-b: The message Received is:" + text);
    }

Consumerc

package Com.yuezhong.queue.consumer;
Import Org.springframework.jms.annotation.JmsListener;

Import org.springframework.stereotype.Component;
 /** * Created by Yz.shi on 2018/4/9.
    * * @Component public class Consumerc {/** * use Jmslistener to configure consumer listening queues * * @param text received message * * @JmsListener (Destination = "out.queue") public void Consumermessage (String text) {System.out.println ("consum
    Er-c: The reply message received from the Out.queue queue is: "+ text"; }
}
Package Com.yuezhong;
Import Com.yuezhong.queue.producer.Producer;
Import Org.apache.activemq.command.ActiveMQQueue;
Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.boot.SpringApplication;
Import org.springframework.boot.autoconfigure.SpringBootApplication;
Import javax.annotation.PostConstruct;

Import javax.jms.Destination;

    @SpringBootApplication public class Activemqapplication {@Autowired private Producer Producer;
        @PostConstruct public void init () {int num = 10;
            try {Destination DestinationQueue = new Activemqqueue ("Yzshi_queue");  for (int i = 1; I <= num i++) {producer.convertandsend (DestinationQueue, "This is the primary queueproducer sent the first" + i + "a message.
            "); System.out.println ("Activemq production succeeded.")
        "); The catch (Exception e) {System.out.println ("Activemq production failed.")
       "); }} public static void Main (string[] args) {SpringapPlication.run (Activemqapplication.class, args);
 }

}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.