1. 程式人生 > >Spring Boot學習筆記(Spring Boot 和 activeMQ整合)

Spring Boot學習筆記(Spring Boot 和 activeMQ整合)

Spring Boot學習筆記

Spring Boot:並不是不對 Spring 功能上的增強,而是提供了一種快速使用 Spring 的方式。

使用步驟:

1、起步依賴:pom.xml中配置起步依賴,會自動匯入spring相關的許多jar包

 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
	<version>1.4.0.RELEASE</version>
 </parent> 
 <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
 </dependencies>

2、變更JDK版本:預設是1.6,在pom.xml中新增版本屬性

 	 <properties>  
    		<java.version>你需要的版本</java.version>
  	  </properties>

3、建立引導類:固定寫法,直接複製就可以

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
       SpringApplication.run(Application.class, args);
    }
}

@SpringBootApplication其實就是以下三個註解的總和 @Configuration: 用於定義一個配置類 @EnableAutoConfiguration :Spring Boot會自動根據你jar包的依賴來自動配置專案。 @ComponentScan: 告訴Spring 哪個packages 的用註解標識的類 會被spring自動掃描並且裝入bean容器。

4、直接進行專案開發,無需配置DispatcherServlet和Spring其他的配置 ***需要修改的一些常用屬性:配置一個application.properties檔案 埠號:server.port=你要的埠號 activemq的地址:spring.activemq.broker-url=你的地址

5、熱部署:在pom.xml配置:

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-devtools</artifactId> 
</dependency>

以後修改程式碼後就不要重啟服務,而是實現了熱部署。

6、Spring Boot 和 activeMQ整合 a、在pom.xml中新增activeMQ的起步依賴

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

b、訊息生產者:

@RestController
public class QueueController {
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
 
    @RequestMapping("/send")
    public void send(String text){
        jmsMessagingTemplate.convertAndSend("spring_boot", text);
    }
}

c、訊息消費者:

@Component
public class Consumer {
    @JmsListener(destination="itcast")
    public void readMessage(String text){
        System.out.println("接收到訊息:"+text);
    }  
}

注意:如果不在application.properties增加spring.activemq.broker-url配置, 指定ActiveMQ的地址,則會使用Spring Boot自帶的訊息機制而不是使用activeMQ.