rabbitmq是实现了高级消息队列协议(amqp)的开源消息代理软件,也成为面向消息的中间件。RabbitMQ服务器是用高性能,可伸缩而闻名的Erlang语言编写而成的,其集群和故障转移是构建在开放电信平台框架上的。
RabbitMQ的安装这里不重复说明,可以参考centos7自学之7-rabbitmq的安装与配置,这里介绍spring cloud使用RabbitMQ。
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>1.5.9.RELEASEversion>
<relativePath />
parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-dependenciesartifactId>
<version>Edgware.RELEASEversion>
<type>pomtype>
<scope>importscope>
dependency>
dependencies>
dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-amqpartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
dependency>
dependencies>
@SpringBootApplication
public class SpringCloudServerBusRabbitmq {
public static void main(String[] args) {
new SpringApplicationBuilder(SpringCloudServerBusRabbitmq.class)
.web(true)
.run(args)
;
}
}
spring:
rabbitmq:
host: 192.168.175.128
port: 5672
username: admin
password: admin
application:
name: springcloud-server-bus-rabbitmq
@Configuration
public class RabbitMqConfig {
public static final String queueName = "springcloud-server-bus-rabbitmq" ;
public Queue rabbitMqQueue(){
return new Queue(queueName);
}
}
@Component
public class Prodecer {
private final Logger _logger = LoggerFactory.getLogger(this.getClass()) ;
@Autowired
private AmqpTemplate rabbitMqTemplate ;
public void send(){
String context = "hello" + new Date() ;
_logger.info("正在向队列发送消息:{}",context);
this.rabbitMqTemplate.convertAndSend(RabbitMqConfig.queueName,context);
}
}
@Component
@RabbitListener(queues = RabbitMqConfig.queueName)
public class Consumer {
private final Logger _logger = LoggerFactory.getLogger(this.getClass()) ;
@RabbitHandler
public void consumer(String message){
_logger.info("从队列获取到的消息:{}",message);
}
}
@Controller
@RequestMapping("/api/rest")
public class RestfulController {
@Autowired
Prodecer prodecer ;
@GetMapping("/message")
public void message(){
prodecer.send();
}
}
启动springcloud-server-bus-rabbitmq。
调用服务:http://localhost:8080/api/rest/message,其效果如下图。
springcloud-server-bus-rabbitmq
springcloud实战之1 技术选型:dubbo还是springcloud
springcloud实战之2 服务注册与发现(eureka实现)
springcloud实战之3 高可用服务注册中心(eureka集群)
springcloud实战之5 服务消费者(ribbon)
springcloud实战之6 服务消费者(Feign)
springcloud实战之7 断路器(Hystrix)
springcloud实战之8 断路器-仪表盘-单例监控(Hystrix)
springcloud实战之9断路器-集群监控(turbine)
springcloud实战之10 分布式配置中心(config)
springcloud实战之11路由网关(zuul)
springcloud实战之12 路由网关拦截器