springboot整合 rabbitmq

作者: 88b61f4ab233 | 来源:发表于2019-06-29 17:46 被阅读2次

1 添加依赖

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

2 添加配置文件

rabbitmq:
  password: admin
  port: 5672
  host: 139.199.33.78
  username: admin

3 创建配置类 实例化队列 交换机 且绑定

@Configuration
public class SenderConf3 {

    @Bean(name="Amessage")
    public Queue AMessage() {
        return new Queue("fanout.A");
    }


    @Bean(name="Bmessage")
    public Queue BMessage() {
        return new Queue("fanout.B");
    }

    @Bean(name="Cmessage")
    public Queue CMessage() {
        return new Queue("fanout.C");
    }

    @Bean
    FanoutExchange fanoutExchange() {
        return new FanoutExchange("fanoutExchange");//配置广播路由器
    }

    @Bean
    Binding bindingExchangeA(@Qualifier("Amessage") Queue AMessage, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(AMessage).to(fanoutExchange);
    }

    @Bean
    Binding bindingExchangeB(@Qualifier("Bmessage") Queue BMessage, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(BMessage).to(fanoutExchange);
    }

    @Bean
    Binding bindingExchangeC(@Qualifier("Cmessage") Queue CMessage, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(CMessage).to(fanoutExchange);
    }

}

4 创建sender类发送消息

@Component
public class HelloSender {
    @Autowired
    private AmqpTemplate template;

    public void send() {
        template.convertAndSend("queue","hello,rabbit~");
    }

    public void send2(){
        template.convertAndSend("exchange","topic.message","hello,rabbit1");
    }
    public void send3(){
        template.convertAndSend("fanoutExchange","topic.message","hello,rabbit2");
    }

}

5 适当的方法调用sender类

@RequestMapping("/userLogin")
public String login(HttpSession session, String username, String password, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
    List<Userinfo> list = service.findUserByUserName(username);
    if (list.size() > 0 && list != null) {
        Userinfo user = list.get(0);
        if (user.getPassword().equals(MD5Utils.md5(password))) {
            if (user.getUsertype() != Constant.ADMIN) {
                model.addAttribute("info", "权限不足");
                return "login";
            }
            user.setUserstatus(1);
            service.update(user);
            helloSender.send();
            helloSender.send2();
            helloSender.send3();
            session.setAttribute("loginUser", user);
            return "home";
        } else {
            model.addAttribute("info", "用户名或密码错误");
            return "login";
        }
    }
    model.addAttribute("info", "用户名或密码错误");
    return "login";
}

相关文章

网友评论

    本文标题:springboot整合 rabbitmq

    本文链接:https://www.haomeiwen.com/subject/jgjpcctx.html