Spring Boot集成六大常用中间件,附集成源码,亲测有效
Spring Boot 整合常见的六大中间件,包括:
- 消息队列(MQ): RabbitMQ / Kafka
- 缓存数据库: Redis
- 数据库: MySQL
- 配置中心: Spring Cloud Config
- 服务注册与发现: Eureka
- 服务调用: OpenFeign
以下是简化的整合示例代码:
- RabbitMQ 配置
@Configuration
public class RabbitMQConfig {
@Bean
public Queue myQueue() {
return new Queue("myQueue", true);
}
}
- Redis 配置
@Configuration
public class RedisConfig {
@Bean
public LettuceConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory(); // 配置连接信息
}
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
return template;
}
}
- MySQL 配置
@Configuration
@EnableJpaRepositories(basePackages = "com.example.repository")
@EnableTransactionManagement
public class MySQLConfig {
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
em.setPackagesToScan("com.example.entity");
em.setJpaVendorAdapter(jpaVendorAdapter);
return em;
}
@Bean
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public JpaVendorAdapter jpaVendorAdapter() {
return new HibernateJpaVendorAdapter();
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
- Spring Cloud Config 配置
@Configuration
public class ConfigServerConfig {
@Bean
public ConfigService configService() {
/
评论已关闭