zoukankan      html  css  js  c++  java
  • SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

    1. activemq

      首先引入依赖

      pom.xml文件

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

      创建一个配置队列类

      JMSConfiguration.java

    复制代码
    package com.wangx.boot.util;
    
    import org.apache.activemq.command.ActiveMQQueue;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.jms.annotation.EnableJms;
    
    import javax.jms.Destination;
    
    @Configuration
    @EnableJms
    public class JMSConfiguration {
    
        @Bean
        public Destination createDestination () {
            return new ActiveMQQueue("com.wangx");
        }
    }
    复制代码

      创建一个消息生产者和消息消费者

      

    复制代码
    package com.wangx.boot.mq;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jms.annotation.JmsListener;
    import org.springframework.jms.core.JmsMessagingTemplate;
    import org.springframework.stereotype.Component;
    
    import javax.jms.Destination;
    @Component
    public class JMSComponent {
    
        @Autowired
        private JmsMessagingTemplate jmsMessagingTemplate;
    
        @Autowired
        private Destination destination;
    
        public void send (String message) {
            jmsMessagingTemplate.convertAndSend(destination, message);
        }
    
        @JmsListener(destination = "com.wangx")
        public void listener (String message) {
            System.out.println("接收到的消息:" + message);
        }
    }
    复制代码

      @JmsListener中的destination必须与队列配置类中定一的queue的名字相同。

       SpringBoot提供了一个默认内置的消息队列中间件,如果我们使用spring.activemq.in-memory=true时将会使用内置的消息队列,但是它也提供了我们使用外部activemq的一些配置:

      

    复制代码
    #spring.activemq.broker-url= 
    #spring.activemq.password= 
    #spring.activemq.user= 
    #spring.activemq.packages.trust-all=false
    #spring.activemq.packages.trusted=
    #spring.activemq.pool.configuration.*= 
    #spring.activemq.pool.enabled=false
    #spring.activemq.pool.expiry-timeout=0
    #spring.activemq.pool.idle-timeout=30000
    #spring.activemq.pool.max-connections=1
    复制代码

      测试消息发送

      

    复制代码
    package com.wangx.boot.controller;
    
    import com.wangx.boot.mq.JMSComponent;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    @RequestMapping("/mq")
    public class JMSController {
    
    
        @Autowired
        private JMSComponent jmsComponent;
    
        @RequestMapping("/send")
        @ResponseBody
        public String send(String msg) {
            jmsComponent.send(msg);
            return msg;
        }
    }
    复制代码

      当访问localhost:8080/mq/send?msg=xxx时,消费者的监听方法(带有@JmsListener注解的方法)会自动监听到消息,并打印到控制台上。

    2. rabbitmq的使用

      首先引入pom.xml 

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

    ps:rabbitmq和activemq的依赖不能同时存在。

      首先还是创建一个队列配置类

      AMQConfiguration.java

    复制代码
    package com.wangx.boot.util;
    
    import org.springframework.amqp.core.Queue;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class AMQConfiguration {
    
        @Bean
        public Queue queue() {
            return new Queue("hello", true);
        }
    
    }
    复制代码

      接着创建消息生产和消费组件

    复制代码
    package com.wangx.boot.mq;
    
    import org.springframework.amqp.core.AmqpTemplate;
    import org.springframework.amqp.core.Queue;
    import org.springframework.amqp.rabbit.annotation.RabbitListener;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    @Component
    public class AMQComponent {
    
        @Autowired
        private AmqpTemplate amqpTemplate;
    
        public void send(String message) {
            amqpTemplate.convertAndSend("hello", message);
        }
    
        @RabbitListener(queues = "hello")
        public void receiveQueue(String text) {
            System.out.println("接受到:" + text);
        }
    }
    复制代码

      在SpringBoot的启动类上添加@EnableRabbit表示开启rabbit消息队列。

      测试是否发送了消息

      

    复制代码
    package com.wangx.boot.controller;
    
    import com.wangx.boot.mq.AMQComponent;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    @RequestMapping("/amq")
    public class AMQController {
    
        @Autowired
        private AMQComponent amqComponent;
    
        @RequestMapping("/send")
        @ResponseBody
        public String send(String  msg) {
            amqComponent.send(msg);
            return msg;
        }
    }
    复制代码

      访问localhost:8080/amq/send?msg=xxx,在调用放松消息的方法时。监听的方法同样会收到消息,并打印到控制台上。

    3. 调用rest服务

      3.1 代码实现

        首先引入依赖

        pom文件

    <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
    </dependency>

      然后随便写一个Controller接口,如:

    复制代码
    package com.wangx.boot.controller;
    
    import com.wangx.boot.cache.CachingBook;
    import com.wangx.boot.entity.Book;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    
    
    @RestController
    @RequestMapping("/api")
    public class ApiController {
    
        @Autowired
        private CachingBook cachingBook;
    
        @RequestMapping(value = "/select", method = RequestMethod.GET)
        public Book get(@RequestParam(defaultValue = "遮天") String name) {
            Book book = cachingBook.findById(name);
            return book;
        }
    
        @RequestMapping(value = "/update", method = RequestMethod.GET)
        public Book update(@RequestParam(defaultValue = "遮天") String name) {
            Book bean = cachingBook.findById(name);
            bean.setAuthor("耳根");
            cachingBook.updateById(bean);
            return bean;
        }
    
        @RequestMapping(value = "/del", method = RequestMethod.GET)
        public String del(@RequestParam(defaultValue = "遮天") String name) {
            return cachingBook.deleteById(name);
        }
    }
    复制代码

      启动服务,在另一个工程中使用RestTemplateBuilder来访问我们启动的服务,

    复制代码
    @Autowired
        private RestTemplateBuilder restTemplateBuilder;
    
            /**
             * get请求
             */
            @Test
            public void getForObject() {
                //发送get请求
                String res = restTemplateBuilder.build().getForObject("http://localhost:8080/api/select",String.class, "遮天");
                System.out.println(res);
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("name", "遮天");
                //发送post请求
                res = restTemplateBuilder.build().postForObject("http://localhost:8080/api/update", map, String.class);
                System.out.println(res);
            }
    复制代码

      可以成功调用我们启动的服务的接口。

      3.2 使用代理 

        使用RestTemplate还可以自己实现代理的功能。

      

    复制代码
    public class ProxyCustomizer implements RestTemplateCustomizer {
            @Override
            public void customize(RestTemplate restTemplate) {
                            //http://ip.zdaye.com/ 上可以查询可用的主机和端口
                String proxyHost = "59.33.46.187";
                int proxyPort = 6969;
                
                HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                HttpClient httpClient = HttpClientBuilder.create().setRoutePlanner(new DefaultProxyRoutePlanner(proxy) {
                    @Override
                    public HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) throws HttpException {
                        
                        return super.determineProxy(target, request, context);
                    }
                }).build();
                HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
                httpComponentsClientHttpRequestFactory.setConnectTimeout(10000);
                httpComponentsClientHttpRequestFactory.setReadTimeout(60000);
                restTemplate.setRequestFactory(httpComponentsClientHttpRequestFactory);
            }
        }
    复制代码

      测试方式:

    String result = restTemplateBuilder.additionalCustomizers(new ProxyCustomizer()).build().getForObject("http://www.baidu.com", String.class);
            System.out.println(result);
  • 相关阅读:
    完全背包详解
    0-1背包详解
    优先队列 + 模拟
    循环节 + 矩阵快速幂
    并查集 + 路径压缩(经典) UVALive 3027 Corporative Network
    dp
    动态规划分类(完整版)
    (二)Spring框架之JDBC的基本使用(p6spy插件的使用)
    (一)Spring框架基础
    (十六)客户端验证与struts2中的服务器端验证
  • 原文地址:https://www.cnblogs.com/leeego-123/p/10900245.html
Copyright © 2011-2022 走看看