小工具知识网

当前位置: 首页 > 行业知识 > Spring Boot集成六大常用中间件,附集成源码,亲测有效

行业知识

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

2026-10-31 06:16:48 来源:互联网转载

目录

      • 万字论文,从0到1,只需1小时
      • 获取途径
      • 1、Spring Boot如何集成Spring Data JPA?
      • 2、Spring Boot如何集成Spring Security?
      • 3、Spring Boot如何集成Redis?
      • 4、Spring Boot如何集成RabbitMQ?
      • 5、Spring Boot如何集成Apache Kafka?
      • 6、Spring Boot如何集成Elasticsearch?

        嗨,你好呀,我是哪吒。

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

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

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

        万字论文,从0到1,只需1小时

        通过OpenAI5月14日1点发布的最新大模型ChatGPT4o:

        • 1小时即可完成万字论文的编写
        • 通过GPT定制的降重大模型“中文论文降重”,2小时即可完成一篇优质的、查重率较低的万字论文。

          在ChatGPT4o对话框中输入:写一个Spring Boot+Vue实现的车位管理系统的论文大纲,并对其具体章节进行详细描述。

          1小时即可完成一份1万字论文的编写。

          获取途径

          现在商家有活动,仅仅需要24.9!!!!

          现在有优惠:

          周卡优惠码是1024,会优惠5元(推荐人写:1024)

          半月卡、月卡、季卡优惠码是102410,会优惠10元。(推荐人写:102410)

          邮箱写自己的邮箱!!!!

          获取途径,网址在下面了:ChatGPT4o,也可以私信哪吒,备注CSDN AI

          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:

                      org.springframework.boot        spring-boot-starter-data-jpa        

          对于 Gradle:

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

          (2)配置数据源

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

          # application.ymlspring:  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.propertiesspring.jpa.hibernate.ddl-auto=updatespring.jpa.show-sql=truespring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

          (4)实体类

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

          @Entitypublic class User {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    private Long id;    private String name;    // getters and setters}

          (5)仓库接口

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

          public interface UserRepository extends JpaRepository {    // 可以添加自定义查询方法    List findByName(String name);}

          (6)使用仓库

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

          @Servicepublic class UserService {    private final UserRepository userRepository;    @Autowired    public UserService(UserRepository userRepository) {        this.userRepository = userRepository;    }    public List findAllUsers() {        return userRepository.findAll();    }    public List findUsersByName(String name) {        return userRepository.findByName(name);    }    // 其他业务方法}

          (7)启动类

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

          @SpringBootApplicationpublic class MyApp {    public static void main(String[] args) {        SpringApplication.run(MyApp.class, args);    }}

          完成以上步骤后,你的 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:

                      org.springframework.boot        spring-boot-starter-security        

          对于 Gradle:

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

          (2)配置 Spring Security

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

          @Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {    @Override    protected void configure(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 等。以下是使用内存数据库进行用户认证的示例:

          @Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {    auth        .inMemoryAuthentication()            .withUser("user").password(passwordEncoder().encode("password")).roles("USER")            .and()            .withUser("admin").password(passwordEncoder().encode("admin")).roles("USER", "ADMIN");}@Beanpublic PasswordEncoder passwordEncoder() {    return new BCryptPasswordEncoder();}

          (5)启动类

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

          @SpringBootApplicationpublic class MyApp {    public static void main(String[] args) {        SpringApplication.run(MyApp.class, args);    }}

          (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的项目,可以添加以下依赖:

                          org.springframework.boot        spring-boot-starter-data-redis        

          确保使用的是与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的接口来简化数据访问层的编码。

          @Repositorypublic interface MyRedisRepository extends CrudRepository {    // 自定义查询方法...}

          (5)注入RedisTemplate

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

          @Servicepublic class MyService {    @Autowired    private StringRedisTemplate redisTemplate;    public void doSomething() {        // 使用redisTemplate操作Redis    }}

          (6)使用 lettuce 或 Jedis 客户端

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

          spring.redis.lettuce.enabled=falsespring.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依赖。

                          org.springframework.boot        spring-boot-starter-amqp        

          (2)配置RabbitMQ

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

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

          (3)配置ConnectionFactory

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

          @Configurationpublic class RabbitMQConfig {    @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@EnableRabbitpublic class RabbitMQConfig extends AbstractRabbitListenerContainerFactory {    @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() {        return new MyMessageListener();    }}

          (5)编写消息监听者

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

          public class MyMessageListener implements MessageListener {    @Override    public void onMessage(Message message, Channel channel) throws Exception {        // 处理接收到的消息    }}

          或者使用注解:

          @Componentpublic class MyMessageListener {    @RabbitListener(queues = "myQueue")    public void listen(String message) {        // 处理接收到的字符串消息    }}

          (6)配置交换机和队列

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

          @Beanpublic Queue myQueue() {    return new Queue("myQueue", true);}@Beanpublic FanoutExchange myFanoutExchange() {    return new FanoutExchange("myFanoutExchange");}@Beanpublic 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的依赖。

                          org.springframework.kafka        spring-kafka        

          (2)配置Kafka连接

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

          spring:  kafka:    bootstrap-servers: localhost:9092

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

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

          (3)配置Kafka生产者

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

          @Configuration@EnableKafkapublic class KafkaProducerConfig {    @Bean    public ProducerFactory producerFactory() {        // 创建并配置Kafka生产者工厂        return new DefaultKafkaProducerFactory(producerConfigs());    }    @Bean    public Map producerConfigs() {        Map 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 kafkaTemplate() {        return new KafkaTemplate(producerFactory());    }}

          (4)编写消息生产者

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

          @Servicepublic class KafkaProducerService {    @Autowired    private KafkaTemplate kafkaTemplate;    public void send(String topic, String message) {        kafkaTemplate.send(topic, message);    }}

          (5)配置Kafka消费者

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

          @Configuration@EnableKafkapublic class KafkaConsumerConfig {    @Bean    public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory() {        // 创建并配置Kafka监听器容器工厂        return new ConcurrentKafkaListenerContainerFactory();    }    @Bean    public KafkaListenerAnnotationBeanPostProcessor kafkaListenerAnnotationBeanPostProcessor() {        return new KafkaListenerAnnotationBeanPostProcessor();    }}

          (6)编写消息消费者

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

          @Componentpublic class KafkaConsumerService {    @KafkaListener(topics = "myTopic", groupId = "my-group")    public void listen(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服务器的版本兼容。

                          org.springframework.boot        spring-boot-starter-data-elasticsearch        

          (2)配置Elasticsearch连接:

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

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

          (3)配置Elasticsearch Repositories:

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

          public interface MyElasticsearchRepository extends ElasticsearchRepository {    // 自定义查询方法...}

          (4)配置Elasticsearch客户端

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

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

          (5)编写实体类映射

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

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

          (6)使用ElasticsearchRepository

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

          @Servicepublic class MyEntityService {    @Autowired    private MyElasticsearchRepository repository;    public void save(MyEntity entity) {        repository.save(entity);    }    public List findAll() {        return repository.findAll();    }    // 其他业务逻辑...}

          (7)测试连接:

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

          (8)配置Elasticsearch索引:

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

          (9)高级配置:

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

          3万字80道Java经典面试题总结(2024修订版)- Java基础篇

          2 万字 42 道Java经典面试题总结(2024修订版)- Java集合篇

          4 万字 102 道Java经典面试题总结(2024修订版)- 多线程篇

          10万字208道Java经典面试题总结(2024修订版)- SSM篇

          文章收录于:100天精通Java从入门到就业

          全网最细Java零基础手把手入门教程,系列课程包括:Java基础、Java8新特性、Java集合、高并发、性能优化等,适合零基础和进阶提升的同学。

          哪吒多年工作总结:Java学习路线总结,搬砖工逆袭Java架构师。

          华为OD机试 2023B卷题库疯狂收录中,刷题点这里

          刷的越多,抽中的概率越大,每一题都有详细的答题思路、详细的代码注释、样例测试,发现新题目,随时更新,全天CSDN在线答疑。

          点击下方名片,回复1024,获取《10万字208道Java经典面试题总结(2024修订版).pdf 》

上一篇:ec服务器怎么没了?

下一篇:超级列表框选择秘籍,轻松成为列表选择高手!