當前位置: 妍妍網 > 碼農

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%以上 。