SpringMvc整合rabbitMQ

 

0.我的目录结构

SpringMvc整合rabbitMQ_第1张图片

1.需要依赖的jar包 


    com.rabbitmq
    amqp-client
    3.5.7



    org.springframework.amqp
    spring-amqp
    1.5.6.RELEASE



    org.springframework
    spring-messaging
    4.2.5.RELEASE



    org.springframework.amqp
    spring-rabbit
    1.5.6.RELEASE



    org.springframework.retry
    spring-retry
    1.1.2.RELEASE

2.生产者配置文件 applicationContext-rabbitmq-send.xml



	
	
		
	
	
	
	

	
	
	

	
	
	
	


	
	

    
	
		
			
		
	

	
	
	
	

3.消费者配置文件 applicationContext-rabbitmq-receive.xml




	
	
		
	
	
	
	

	
	

	
	

    
	
		
			
		
	

	
	
	
		
		
	

	

4.引入的配置文件配置 jdbcConfig.properties  (路径错误的话自己修改)

rabbit.host=127.0.0.1
rabbit.port=5672
rabbit.username=zsq
rabbit.password=zsq
rabbit.virtual-host=/zhang
rabbit.direct-exchange=exchangeZhoa

5. applicationContext.xml 引入配置文件 ,添加线程池配置


	
	

	
	
		
		
		
		
		
		
		
		
	
	
	

6.springmvcConfig.xml 配置文件,添加扫包范围

7,核心代码 

 controller控制层,调用发送消息工具类

@RestController
@RequestMapping("/test")
public class RabbitMQTest {

    @Autowired
    private RabbitAckServiceImpl rabbitAckService;

    @RequestMapping("/test2")
    public void sendMessage2() {
        for (int i = 1; i <=100 ; i++) {
            Map map=new HashMap<>();
            map.put("hh","zsq"+i);
            System.out.println("to send message:  "+ map);
            String json = JSON.toJSONString(map);
            boolean zhoa = rabbitAckService.sendMessage("exchangeZhoa111","zhoa", json);
            if(zhoa){
                System.out.println("发送成功1");
            }else {
                System.out.println("发送失败");
            }
        }
    }
}

工具类发送消息 

@Service
public class RabbitAckServiceImpl {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * @param exchange      交换机
     * @param routingKey    路由key
     * @param message       消息
     */
    public boolean sendMessage(String exchange,String routingKey , String message) {
        boolean result=false;
        if(!checkParam(exchange,routingKey,message)){
            return false;
        }
        try {
            rabbitTemplate.convertAndSend(exchange,routingKey,message);
            result = true;
        }catch (AmqpException e){
            e.printStackTrace();
        }
        return result;
    }

    public boolean checkParam(String param1){
        if(StringUtils.isEmpty(param1)){
            return false;
        }else {
            return true;
        }
    }

    public boolean checkParam(String param1,String param2){
        if(StringUtils.isEmpty(param1)||StringUtils.isEmpty(param2)){
            return false;
        }else {
            return true;
        }
    }

    public boolean checkParam(String param1,String param2,String param3){
        if(StringUtils.isEmpty(param1)||StringUtils.isEmpty(param2)||StringUtils.isEmpty(param3)){
            return false;
        }else {
            return true;
        }
    }
}

 实现接口 , 消息发送到exchang交换机 ,  返回投递结果

public class CallBackMQ implements RabbitTemplate.ConfirmCallback {

    int i=1;
    @Override   //消息投递到exchange是否成功
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        if (b) {
            //设置消息投递成功
            System.out.println("消息投递成功"+i);
            i++;
        } else {
            //消息投递失败
            System.out.println(s);
            System.out.println("消息投递失败");
        }
    }
}

 实现接口, 消息从Exchange交换机 发送到 对列Queue 失败时回调执行此方法

public class ReturnCall implements RabbitTemplate.ReturnCallback {
    /**
     *只有消息从Exchange路由到Queue失败才会回调这个方法
     */
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        System.out.println("消息从Exchage路由到Queue失败");
    }
}

消费者消费 ,采用多线程异步消费 

//消费者 采用异步多线程消费
public class CatHandler2 implements ChannelAwareMessageListener {
    
    @Autowired
    private TaskExecutor taskExecutor;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        taskExecutor.execute(new Consume(message,channel));
    }
}

 线程类方法

public class Consume implements  Runnable{

    private Message message;
    private Channel channel;

    public  Consume(Message message, Channel channel){
        this.message=message;
        this.channel=channel;
    }


    @Override
    public void run() {
        boolean falg = false;
        try {
            // msg就是rabbitmq传来的消息,需要的同学自己打印看一眼
            // 使用jackson解析
            Map map = JSON.parseObject(message.getBody(), Map.class);
            System.out.println(Thread.currentThread().getName()+"收到消息:我是可爱的小猪,我的名字是" + map.get("hh"));
            //Thread.sleep(2000);
            falg = true;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            MessageProperties properties = message.getMessageProperties();
            long tag = properties.getDeliveryTag();
            //消费成功后将手动确认消息
            if (falg) {
                //消息确认,发送成功
                try {
                    channel.basicAck(tag, false);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                //如果发送失败,消息会重新进入队列,再次被这个消费者消费
                //消息发送失败后,也可以将消息发送到别的队列,让其他消费者进行消费
                //第三个参数 true为重新将消息放入队列,如果设置为false,则抛弃这条消息
                try {
                    channel.basicNack(tag, false, true);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

8.测试结果

SpringMvc整合rabbitMQ_第2张图片

你可能感兴趣的:(RocketMQ)