以下是一个简化的代码示例,展示如何使用Spring Cloud Stream与RabbitMQ接收数据,并将数据存储到MySQL数据库中。
- 添加依赖到
pom.xml
:
<dependencies>
<!-- Spring Cloud Stream -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
- 配置
application.yml
:
spring:
cloud:
stream:
binders:
rabbit:
type: rabbit
environment:
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
bindings:
input:
destination: data-input
content-type: application/json
binder: rabbit
datasource:
url: jdbc:mysql://localhost:3306/testdb
username: dbuser
password: dbpass
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
show-sql: true
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
- 创建实体类
LinkData.java
:
@Entity
public class LinkData {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String url;
// getters and setters
}
- 创建仓库接口
LinkDataRepository.java
:
public interface LinkDataRepository extends JpaRepository<LinkData, Long> {}
- 创建消息接收器
LinkDataProcessor.java
:
@EnableBinding(Sink.class)
public class LinkDataProcessor {
@Autowired
private LinkDataRepository repository;
@StreamListener(Sink.INPUT)
public void handle(LinkData linkData) {
repository.save(linkData);
}
}
- 启动类
Application.java
:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(App