当前位置: 欣欣网 > 码农

Spring Boot集成六大常用中间件,附集成源码,亲测有效,即插即用!

2024-05-28码农

回复1024,获取13万字445道Java经典面试题pdf

嗨,你好呀,我是哪吒。

面试的时候总是被问到一些中间件的使用,比如Redis、Kafka、Elasticsearch等。很多小伙伴回答的都不尽如人意, 自己虽然用过、或者照着视频敲过,也实现过,但总感觉差了点什么。

因为你没有进行系统的总结过,对比过。

下面就针对几个常见的中间件 Spring Data JPA、 Spring Security、Redis、RabbitMQ、Kafka、Elasticsearch ,简述一下它们与SpringBoot的集成方案,从0到1,从yml配置到调用API实现代码逻辑,做到真正意义上的即插即用。

1、Spring Boot如何集成Spring Data JPA?

Spring Data JPA 是 Spring 框架的一个模块,它简化了与 Java 持久化 API (JPA) 的交互,提供了一种声明式的数据访问。在 Spring Boot 应用中集成 Spring Data JPA 可以提高数据访问层的效率。以下是集成 Spring Data JPA 的基本步骤:

(1)添加依赖

首先,需要在项目的 pom.xml(Maven)或 build.gradle(Gradle)文件中添加 Spring Data JPA 的依赖。

对于 Maven:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- 其他依赖 -->
</dependencies>

对于 Gradle:

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
// 其他依赖
}

(2)配置数据源

在 application.properties 或 application.yml 文件中配置数据库连接信息。

# application.yml
spring:
datasource:
url:jdbc:mysql://localhost:3306/your_database
username:your_username
password:your_password
driver- class-name:com.mysql.cj.jdbc.Driver

(3)配置 JPA

同样在配置文件中,配置 JPA 的相关属性,如实体扫描位置、数据库方言等。

# application.properties
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

(4)实体类

创建 JPA 实体类,使用 JPA 注解来映射数据库表和列。

@Entity
public classUser{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// getters and setters
}

(5)仓库接口

创建一个继承 JpaRepository 的接口,Spring Data JPA 会根据接口方法名称自动实现数据访问逻辑。

publicinterfaceUserRepositoryextendsJpaRepository<UserLong{
// 可以添加自定义查询方法
List<User> findByName(String name);
}

(6)使用仓库

在服务层注入 UserRepository 并使用它来执行数据操作。

@Service
public classUserService{
privatefinal UserRepository userRepository;
@Autowired
publicUserService(UserRepository userRepository){
this.userRepository = userRepository;
}
public List<User> findAllUsers(){
return userRepository.findAll();
}
public List<User> findUsersByName(String name){
return userRepository.findByName(name);
}
// 其他业务方法
}

(7)启动类

确保你的 Spring Boot 启动类上有 @SpringBootApplication 注解,这样 Spring Boot 才能自动扫描并加载配置。

@SpringBootApplication
public classMyApp{
publicstaticvoidmain(String[] args){
SpringApplication.run(MyApp. classargs);
}
}

完成以上步骤后,你的 Spring Boot 应用就可以使用 Spring Data JPA 进行数据库操作了。Spring Data JPA 提供了大量简化 CRUD 操作的方法,同时也支持通过方法名定义查询,极大地提高了开发效率。

2、Spring Boot如何集成Spring Security?

Spring Security 是一个功能强大且可高度定制的身份验证和访问控制框架。在 Spring Boot 应用中集成 Spring Security 可以提供安全的用户认证和授权机制。以下是集成 Spring Security 的基本步骤:

(1)添加依赖

首先,在项目的 pom.xml(Maven)或 build.gradle(Gradle)文件中添加 Spring Security 的依赖。

对于 Maven:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- 其他依赖 -->
</dependencies>

对于 Gradle:

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-security'
// 其他依赖
}

(2)配置 Spring Security

创建一个配置类,继承 WebSecurityConfigurerAdapter 并重写相应的方法来定义安全策略。

@Configuration
@EnableWebSecurity
public classSecurityConfigextendsWebSecurityConfigurerAdapter{
@Override
protectedvoidconfigure(HttpSecurity http)throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll() // 允许所有用户访问首页
.anyRequest().authenticated() // 其他所有请求需要认证
.and()
.formLogin()
.loginPage("/login") // 定制登录页
.permitAll()
.and()
.logout()
.permitAll();
}
// 可以添加更多的安全配置
}

(3)创建登录页

Spring Security 会根据 configure(HttpSecurity http) 方法中定义的 loginPage 路径来寻找登录页。你可以创建一个自定义的登录页,或者使用 Spring Boot 默认提供的登录页。

(4)用户认证

Spring Security 支持多种用户认证方式,包括内存数据库、JDBC 数据库、LDAP 等。以下是使用内存数据库进行用户认证的示例:

@Autowired
publicvoidconfigureGlobal(AuthenticationManagerBuilder auth)throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password(passwordEncoder().encode("password")).roles("USER")
.and()
.withUser("admin").password(passwordEncoder().encode("admin")).roles("USER""ADMIN");
}
@Bean
public PasswordEncoder passwordEncoder(){
returnnew BCryptPasswordEncoder();
}

(5)启动类

确保你的 Spring Boot 启动类上有 @SpringBootApplication 注解,这样 Spring Boot 才能自动扫描并加载配置。

@SpringBootApplication
public classMyApp{
publicstaticvoidmain(String[] args){
SpringApplication.run(MyApp. classargs);
}
}

(6)自定义安全配置

根据需要,你可以添加更多的安全配置,如密码策略、记住我功能、CORS 过滤器、自定义权限验证等。

(7)测试

启动应用并访问受保护的资源,以确保安全配置按预期工作。

通过以上步骤,你可以在 Spring Boot 应用中集成 Spring Security,实现用户认证和授权。Spring Security 提供了灵活的扩展点,允许你根据应用的具体需求定制安全策略。

3、Spring Boot如何集成Redis?

在Spring Boot中集成Redis是一个相对简单的过程,主要得益于Spring Boot对各种存储解决方案的自动配置支持。

以下是集成Redis的基本步骤:

(1)添加依赖

首先,需要在项目的pom.xml文件中添加Spring Boot对Redis支持的依赖。对于使用Spring Data Redis的项目,可以添加以下依赖:

<dependencies>
<!-- Spring Boot Starter Data Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 其他依赖 -->
</dependencies>

确保使用的是与Spring Boot版本兼容的Redis依赖版本。

(2)配置Redis服务器

在application.properties或application.yml文件中配置Redis服务器的地址和端口。

spring:
redis:
host:127.0.0.1
port:6379
password:123456

(3)自动配置

Spring Boot将自动配置Spring Data Redis连接工厂和操作库,无需手动配置。

(4)使用RedisRepository

如果你使用Spring Data Redis,可以创建一个继承RedisRepository的接口来简化数据访问层的编码。

@Repository
publicinterfaceMyRedisRepositoryextendsCrudRepository<MyEntityString{
// 自定义查询方法...
}

(5)注入RedisTemplate

在需要使用Redis的组件中,注入StringRedisTemplate或RedisTemplate来执行各种操作。

@Service
public classMyService{
@Autowired
private StringRedisTemplate redisTemplate;
publicvoiddoSomething(){
// 使用redisTemplate操作Redis
}
}

(6)使用 lettuce 或 Jedis 客户端

从Spring Boot 2.0开始,默认的Redis客户端是lettuce。如果你更喜欢使用Jedis,可以在application.properties中配置:

spring.redis.lettuce.enabled=false
spring.redis.jedis.enabled=true

(7)配置SSL连接

如果Redis服务器配置了SSL,需要添加相关依赖并配置SSL连接。

(8)集群支持

如果使用Redis集群,需要配置集群节点信息:

spring.redis.cluster.nodes=127.0.0.1:7000,127.0.0.1:7001

(9)测试连接

启动应用程序后,可以通过注入的RedisTemplate或自定义的Repository来测试Redis连接是否成功。

(10)使用Spring Cache

如果你想要利用Redis作为Spring的缓存提供者,可以添加spring-boot-starter-cache依赖,并在配置中启用对Redis的缓存支持。

4、Spring Boot如何集成RabbitMQ?

在Spring Boot中集成RabbitMQ主要涉及以下步骤:

(1)添加依赖

在项目的pom.xml文件中添加RabbitMQ的Spring Boot Starter依赖。

<dependencies>
<!-- Spring Boot Starter for RabbitMQ -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!-- 其他依赖 -->
</dependencies>

(2)配置RabbitMQ

在application.properties或application.yml中配置RabbitMQ服务器的连接信息。

spring:
rabbitmq:
addresses:127.0.0.1
username:guest
password:guest

(3)配置ConnectionFactory

如果需要自定义ConnectionFactory,可以创建一个配置类并使用@Configuration注解。在该类中,可以使用@Bean注解来声明一个ConnectionFactory。

@Configuration
public classRabbitMQConfig{
@Bean
public ConnectionFactory connectionFactory(){
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("127.0.0.1");
factory.setUsername("guest");
factory.setPassword("guest");
return factory;
}
}

(4)配置RabbitMQ的Listener容器

使用SimpleMessageListenerContainer作为消息监听容器。在配置类中声明并配置它:

@Configuration
@EnableRabbit
public classRabbitMQConfigextendsAbstractRabbitListenerContainerFactory{
@Autowired
private ConnectionFactory connectionFactory;
@Override
protected ConnectionFactory getConnectionFactory(){
return connectionFactory;
}
@Bean
public SimpleMessageListenerContainer container(){
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setQueueNames("myQueue");
container.setMessageListener(messageListener());
return container;
}
@Bean
public MessageListener messageListener(){
returnnew MyMessageListener();
}
}


(5)编写消息监听者

创建一个消息监听者,实现MessageListener接口或使用@RabbitListener注解。

public classMyMessageListenerimplementsMessageListener{
@Override
publicvoidonMessage(Message message, Channel channel)throws Exception {
// 处理接收到的消息
}
}

或者使用注解:

@Component
public classMyMessageListener{
@RabbitListener(queues = "myQueue")
publicvoidlisten(String message){
// 处理接收到的字符串消息
}
}

(6)配置交换机和队列

如果需要,可以配置自定义的交换机和队列,以及它们之间的绑定关系。

@Bean
public Queue myQueue(){
returnnew Queue("myQueue"true);
}
@Bean
public FanoutExchange myFanoutExchange(){
returnnew FanoutExchange("myFanoutExchange");
}
@Bean
public Binding myBinding(){
return BindingBuilder.bind(myQueue()).to(myFanoutExchange());
}

(7)测试连接

启动应用程序后,可以通过发送和接收消息来测试RabbitMQ连接是否成功。

(8)配置管理端点

如果你希望Spring Boot暴露RabbitMQ的健康和信息端点,可以添加以下配置:

management.endpoints.web.exposure.include=health,info,rabbitmq

(9)高级配置

根据需要,可能还需要配置其他高级特性,如消息确认、事务、TTL(消息存活时间)、死信交换机等。

5、Spring Boot如何集成Apache Kafka?

在Spring Boot中集成Apache Kafka主要涉及以下步骤:

(1)添加依赖:

在项目的pom.xml文件中添加Spring for Apache Kafka的依赖。

<dependencies>
<!-- Spring Boot Starter for Apache Kafka -->
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<!-- 其他依赖 -->
</dependencies>

(2)配置Kafka连接

在application.properties或application.yml中配置Kafka的连接信息。

spring:
kafka:
bootstrap-servers:localhost:9092

如果需要配置更多的Kafka属性,比如消费者组、序列化器等,可以继续添加:

spring.kafka.consumer.group-id=my-group
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer

(3)配置Kafka生产者

创建一个配置类,并通过@EnableKafka注解启用Kafka配置,并定义Kafka生产者的相关配置。

@Configuration
@EnableKafka
public classKafkaProducerConfig{
@Bean
public ProducerFactory<String, String> producerFactory(){
// 创建并配置Kafka生产者工厂
returnnew DefaultKafkaProducerFactory<>(producerConfigs());
}
@Bean
public Map<String, Object> producerConfigs(){
Map<String, Object> props = new HashMap<>();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ProducerConfig.KEY_SERIALIZER_ class_CONFIG, StringSerializer. class);
props.put(ProducerConfig.VALUE_SERIALIZER_ class_CONFIG, StringSerializer. class);
return props;
}
@Bean
public KafkaTemplate<String, String> kafkaTemplate(){
returnnew KafkaTemplate<>(producerFactory());
}
}

(4)编写消息生产者

创建一个生产者,使用KafkaTemplate发送消息。

@Service
public classKafkaProducerService{
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
publicvoidsend(String topic, String message){
kafkaTemplate.send(topic, message);
}
}

(5)配置Kafka消费者

创建一个配置类,定义Kafka消费者的相关配置,并启用Kafka监听器。

@Configuration
@EnableKafka
public classKafkaConsumerConfig{
@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory(){
// 创建并配置Kafka监听器容器工厂
returnnew ConcurrentKafkaListenerContainerFactory<>();
}
@Bean
public KafkaListenerAnnotationBeanPostProcessor kafkaListenerAnnotationBeanPostProcessor(){
returnnew KafkaListenerAnnotationBeanPostProcessor();
}
}

(6)编写消息消费者

创建一个消费者,使用@KafkaListener注解来监听特定主题的消息。

@Component
public classKafkaConsumerService{
@KafkaListener(topics = "myTopic", groupId = "my-group")
publicvoidlisten(String message){
// 处理接收到的消息
}
}

(7)测试连接

启动应用程序后,可以通过发送消息到Kafka主题并查看消费者是否能够接收到消息来测试Kafka连接是否成功。

(8)配置管理端点

如果你希望Spring Boot暴露Kafka的健康和信息端点,可以添加以下配置:

management.endpoints.web.exposure.include=health,info,kafka

(9)高级配置

根据需要,可能还需要配置其他高级特性,如事务管理、自定义分区器、自定义序列化器等。

6、Spring Boot如何集成Elasticsearch?

在Spring Boot中集成Elasticsearch主要涉及以下步骤:

(1)添加依赖

在项目的pom.xml文件中添加Spring Data Elasticsearch的依赖。确保你使用的版本与Elasticsearch服务器的版本兼容。

<dependencies>
<!-- Spring Boot Starter Data Elasticsearch -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- 其他依赖 -->
</dependencies>

(2)配置Elasticsearch连接:

在application.properties或application.yml中配置Elasticsearch服务器的连接信息。

spring:
elasticsearch:
rest:
uris:"http://localhost:9200"

(3)配置Elasticsearch Repositories:

如果你使用Spring Data Elasticsearch,可以创建一个继承ElasticsearchRepository的接口来简化数据访问层的编码。

publicinterfaceMyElasticsearchRepositoryextendsElasticsearchRepository<MyEntityString{
// 自定义查询方法...
}

(4)配置Elasticsearch客户端

如果需要自定义Elasticsearch客户端,可以创建一个配置类并使用@Configuration注解。在该类中,可以使用@Bean注解来声明一个RestHighLevelClient。

@Configuration
public classElasticsearchConfig{
@Bean
public RestHighLevelClient elasticsearchClient(){
final HttpClient httpClient = HttpClientBuilder.create().build();
final HttpHost httpHost = new HttpHost("localhost"9200"http");
returnnew RestHighLevelClient(httpClient, RestClientBuilder.HttpClientConfigCallback(), Collections.singletonList(httpHost));
}
}

(5)编写实体类映射

定义实体类,并使用注解标注实体类属性以映射到Elasticsearch的索引字段。

@Document(indexName = "my_index")
public classMyEntity{
@Id
private String id;
@Field(type = FieldType.Text)
private String text;
// 其他字段和getter/setter
}

(6)使用ElasticsearchRepository

注入ElasticsearchRepository并在业务逻辑中使用它进行CRUD操作。

@Service
public classMyEntityService{
@Autowired
private MyElasticsearchRepository repository;
publicvoidsave(MyEntity entity){
repository.save(entity);
}
public List<MyEntity> findAll(){
return repository.findAll();
}
// 其他业务逻辑...
}


(7)测试连接:

启动应用程序后,可以通过发送查询到Elasticsearch并检查返回的数据来测试Elasticsearch连接是否成功。

(8)配置Elasticsearch索引:

根据需要,可能还需要配置Elasticsearch的索引设置,如分片、副本、映射等。

(9)高级配置:

根据需要,可能还需要配置其他高级特性,如自定义分析器、索引刷新间隔等。

今天就到这里啦,明天见~

- EOF -

最后给大家推荐一个ChatGPT 4o国内网站,是我们团队一直在使用的,我们对接是OpenAI官网的账号,给大家打造了一个一模一样的ChatGPT,很多粉丝朋友现在也都通过我拿这种号,价格不贵,关键还有售后 。

一句话说明 用官方一半价格的钱,用跟官方 ChatGPT4.0 一模一样功能的工具,而且不需要魔法,直接使用,不用担心网络问题。

包含ChatGPT4.0知识问答、DALL-E AI绘画、图片自动识别、Code Copilot辅助编程、联网查询、毕设去重、BUG解决、代码优化、上传文件、数据分析等。

购买这个账号,一直有售后,不用担心中途封号或者用不了。

也可以加哪吒微信:18640839506,备注:AI,咨询ChatGPT4o使用问题。

网站优点:

  1. 支持OpenAI最新的ChatGPT4o。

  2. 同时支持 PC、手机、平板

  3. 不需要国外特殊网络, 可以直接使用 ,非常方便 。

  4. 个人专属授权码,放心使用。

  5. 官方独立账户规定每3小时40次 4.0提问, 我们这个不限制4.0提问次数

  6. 我们这个不会出现封号的情况,避免你因为封号多花冤枉钱。

  7. 使用期内一直有售后,如果系统故障会补时长,可以放心。

  8. 系统运行非常稳定,用了我们这种账号,次月续费率达到95%以上 。