1658817167
В этой статье вы узнаете, как запустить ksqlDB в Kubernetes и использовать его с Spring Boot. Вы также увидите, как запустить Kafka в Kubernetes на основе оператора Strimzi . Чтобы интегрировать Spring Boot с сервером ksqlDB, мы собираемся использовать облегченный Java-клиент, предоставляемый ksqlDB. Этот клиент поддерживает запросы pull и push. Он также предоставляет API для вставки строк и создания таблиц или потоков. Подробнее об этом можно прочитать в документации ksqlDB здесь .
Наш образец приложения Spring Boot очень прост. Мы будем использовать Supplier
bean-компонент Spring Cloud Stream для генерации и отправки событий в тему Kafka. Дополнительные сведения о Kafka с Spring Cloud Stream см. в следующей статье . С другой стороны, наше приложение получает данные из темы Kafka с помощью запросов kSQL. Он также создается KTable
при запуске.
Давайте посмотрим на нашу архитектуру.
Если вы хотите попробовать это самостоятельно, вы всегда можете взглянуть на мой исходный код. Для этого вам нужно клонировать мой репозиторий GitHub . Затем перейдите в transactions-service
каталог. После этого вы должны просто следовать моим инструкциям. Давайте начнем.
Мы будем использовать несколько инструментов. Тебе нужно иметь:
kubectl
CLI — для взаимодействия с кластеромКонечно, нам нужен экземпляр Kafka для выполнения нашего упражнения. Есть несколько способов запустить Kafka в Kubernetes. Я покажу вам, как это сделать с помощью оператора. На первом этапе вам необходимо установить OLM (диспетчер жизненного цикла оператора) в вашем кластере. Для этого вы можете просто выполнить следующую команду в своем контексте Kubernetes:
$ curl -L https://github.com/operator-framework/operator-lifecycle-manager/releases/download/v0.21.2/install.sh -o install.sh
$ chmod +x install.sh
$ ./install.sh v0.21.2
Затем можно переходить к установке оператора Strimzi. Это всего лишь одна команда.
$ kubectl create -f https://operatorhub.io/install/stable/strimzi-kafka-operator.yaml
Теперь мы можем создать кластер Kafka в Kubernetes. Давайте начнем с выделенного пространства имен для нашего упражнения:
$ kubectl create ns kafka
Я предполагаю, что у вас есть кластер Kubernetes с одним узлом, поэтому мы также создадим Kafka с одним узлом. Вот манифест YAML с Kafka
CRD. Вы можете найти его в репозитории по пути k8s/cluster.yaml
.
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
entityOperator:
topicOperator: {}
userOperator: {}
kafka:
config:
default.replication.factor: 1
inter.broker.protocol.version: "3.2"
min.insync.replicas: 1
offsets.topic.replication.factor: 1
transaction.state.log.min.isr: 1
transaction.state.log.replication.factor: 1
listeners:
- name: plain
port: 9092
tls: false
type: internal
- name: tls
port: 9093
tls: true
type: internal
replicas: 1
storage:
type: jbod
volumes:
- id: 0
type: persistent-claim
size: 30Gi
deleteClaim: true
version: 3.2.0
zookeeper:
replicas: 1
storage:
type: persistent-claim
size: 10Gi
deleteClaim: true
Давайте применим его к Kubernetes в kafka
пространстве имен:
$ kubectl apply -f k8s/cluster.yaml -n kafka
Вы должны увидеть один экземпляр Kafka, а также один экземпляр Zookeeper. Если модули работают, значит, у вас есть Kafka в Kubernetes.
$ kubectl get pod -n kafka
NAME READY STATUS RESTARTS AGE
my-cluster-entity-operator-68cc6bc4d9-qs88p 3/3 Running 0 46m
my-cluster-kafka-0 1/1 Running 0 48m
my-cluster-zookeeper-0 1/1 Running 0 48m
Kafka доступна внутри кластера под именем my-cluster-kafka-bootstrap
и портом 9092
.
kubectl get svc -n kafka
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
my-cluster-kafka-bootstrap ClusterIP 10.108.109.255 <none> 9091/TCP,9092/TCP,9093/TCP 47m
my-cluster-kafka-brokers ClusterIP None <none> 9090/TCP,9091/TCP,9092/TCP,9093/TCP 47m
my-cluster-zookeeper-client ClusterIP 10.102.10.251 <none> 2181/TCP 47m
my-cluster-zookeeper-nodes ClusterIP None <none> 2181/TCP,2888/TCP,3888/TCP 47m
Сервер KsqlDB является частью Confluent Platform. Поскольку мы устанавливаем не всю платформу Confluent на Kubernetes, а только кластер Kafka с открытым исходным кодом, нам нужно установить KsqlDB Server отдельно. Давайте сделаем это с Хелмом. Для сервера KSQL нет «официальной» диаграммы Helm. Поэтому нам следует сразу перейти к репозиторию Confluent Helm на GitHub:
$ git clone https://github.com/confluentinc/cp-helm-charts.git
$ cd cp-helm-charts
В этом репозитории вы можете найти отдельные диаграммы Helm для каждого отдельного компонента Confluent, включая, например, центр управления или KSQL Server. Расположение нашей диаграммы внутри репозитория — charts/cp-ksql-server
. Нам нужно переопределить некоторые настройки по умолчанию во время установки. Прежде всего, мы должны отключить безголовый режим. В автономном режиме KSQL Server не предоставляет конечную точку HTTP и загружает запросы из входного скрипта. Наше приложение Spring Boot будет подключаться к серверу через HTTP. На следующем шаге мы должны переопределить адрес кластера Kafka по умолчанию и версию KSQL Server по умолчанию, которая все еще 6.1.0
существует. Мы будем использовать последнюю версию 7.1.1
. Вот helm
команда, которую вы должны запустить в своем кластере Kubernetes:
$ helm install cp-ksql-server \
--set ksql.headless=false \
--set kafka.bootstrapServers=my-cluster-kafka-bootstrap:9092 \
--set imageTag=7.1.1 \
charts/cp-ksql-server -n kafka
Вот результат:
Давайте проверим, работает ли KSQL в кластере:
$ kubectl get pod -n kafka | grep ksql
cp-ksql-server-679fc98889-hldfv 2/2 Running 0 2m11s
Конечная точка HTTP доступна для других приложений под именем cp-ksql-server
и портом 8088
:
$ kubectl get svc -n kafka | grep ksql
cp-ksql-server ClusterIP 10.109.189.36 <none> 8088/TCP,5556/TCP 3m25s
Теперь у нас есть весь необходимый персонал, работающий в нашем кластере Kubernetes. Поэтому мы можем перейти к реализации приложения Spring Boot.
Готовой интеграции между Spring Boot и ksqlDB я не нашел. Поэтому будем использовать ksqldb-api-client
напрямую. В первом нам нужно включить репозиторий ksqlDB Maven и некоторые зависимости:
<dependencies>
...
<dependency>
<groupId>io.confluent.ksql</groupId>
<artifactId>ksqldb-api-client</artifactId>
<version>0.26.0</version>
</dependency>
<dependency>
<groupId>io.confluent.ksql</groupId>
<artifactId>ksqldb-udf</artifactId>
<version>0.26.0</version>
</dependency>
<dependency>
<groupId>io.confluent.ksql</groupId>
<artifactId>ksqldb-common</artifactId>
<version>0.26.0</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>ksqlDB</id>
<name>ksqlDB</name>
<url>https://ksqldb-maven.s3.amazonaws.com/maven/</url>
</repository>
</repositories>
После этого мы можем определить Spring, @Bean
возвращающий реализацию ksqlDB Client
. Поскольку мы будем запускать наше приложение в том же пространстве имен, что и KSQL Server, нам нужно указать имя службы Kubernetes в качестве имени хоста.
@Configuration
public class KSQLClientProducer {
@Bean
Client ksqlClient() {
ClientOptions options = ClientOptions.create()
.setHost("cp-ksql-server")
.setPort(8088);
return Client.create(options);
}
}
Наше приложение взаимодействует с KSQL Server через конечную точку HTTP. Он создает сингл KTable
при запуске. Для этого нам нужно вызвать executeStatement
метод для экземпляра компонента KSQL Client
. Мы создаем таблицу SOURCE, чтобы разрешить запуск запросов на включение в нее. Таблица получает данные из transactions
топика. Он ожидает формат JSON во входящих событиях.
public class KTableCreateListener implements ApplicationListener<ContextRefreshedEvent> {
private static final Logger LOG = LoggerFactory.getLogger(KTableCreateListener.class);
private Client ksqlClient;
public KTableCreateListener(Client ksqlClient) {
this.ksqlClient = ksqlClient;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
try {
String sql = """
CREATE SOURCE TABLE IF NOT EXISTS transactions_view (
id BIGINT PRIMARY KEY,
sourceAccountId BIGINT,
targetAccountId BIGINT,
amount INT
) WITH (
kafka_topic='transactions',
value_format='JSON'
);
""";
ExecuteStatementResult result = ksqlClient.executeStatement(sql).get();
LOG.info("Result: {}", result.queryId().orElse(null));
} catch (ExecutionException | InterruptedException e) {
LOG.error("Error: ", e);
}
}
}
После создания таблицы мы можем выполнить к ней несколько запросов. Есть довольно простые запросы. Мы пытаемся найти все транзакции и все транзакции, связанные с конкретной учетной записью.
@RestController
@RequestMapping("/transactions")
public class TransactionResource {
private static final Logger LOG = LoggerFactory.getLogger(TransactionResource.class);
Client ksqlClient;
public TransactionResource(Client ksqlClient) {
this.ksqlClient = ksqlClient;
}
@GetMapping
public List<Transaction> getTransactions() throws ExecutionException, InterruptedException {
StreamedQueryResult sqr = ksqlClient
.streamQuery("SELECT * FROM transactions_view;")
.get();
Row row;
List<Transaction> l = new ArrayList<>();
while ((row = sqr.poll()) != null) {
l.add(mapRowToTransaction(row));
}
return l;
}
@GetMapping("/target/{accountId}")
public List<Transaction> getTransactionsByTargetAccountId(@PathVariable("accountId") Long accountId)
throws ExecutionException, InterruptedException {
StreamedQueryResult sqr = ksqlClient
.streamQuery("SELECT * FROM transactions_view WHERE sourceAccountId=" + accountId + ";")
.get();
Row row;
List<Transaction> l = new ArrayList<>();
while ((row = sqr.poll()) != null) {
l.add(mapRowToTransaction(row));
}
return l;
}
private Transaction mapRowToTransaction(Row row) {
Transaction t = new Transaction();
t.setId(row.getLong("ID"));
t.setSourceAccountId(row.getLong("SOURCEACCOUNTID"));
t.setTargetAccountId(row.getLong("TARGETACCOUNTID"));
t.setAmount(row.getInteger("AMOUNT"));
return t;
}
}
Наконец, мы можем перейти к последней части нашего упражнения. Нам нужно сгенерировать тестовые данные и отправить их в transactions
топик Kafka. Самый простой способ добиться этого — с помощью модуля Spring Cloud Stream Kafka. Во-первых, давайте добавим следующую зависимость Maven:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-kafka</artifactId>
</dependency>
Затем мы можем создать производителя на основе Supplier
bean-компонента Spring. Бин Supplier
постоянно генерирует и отправляет новые события в целевой канал. По умолчанию действие повторяется раз в секунду.
@Configuration
public class KafkaEventProducer {
private static long transactionId = 0;
private static final Random r = new Random();
@Bean
public Supplier<Message<Transaction>> transactionsSupplier() {
return () -> {
Transaction t = new Transaction();
t.setId(++transactionId);
t.setSourceAccountId(r.nextLong(1, 100));
t.setTargetAccountId(r.nextLong(1, 100));
t.setAmount(r.nextInt(1, 10000));
Message<Transaction> o = MessageBuilder
.withPayload(t)
.setHeader(KafkaHeaders.MESSAGE_KEY, new TransactionKey(t.getId()))
.build();
return o;
};
}
}
Конечно, нам также нужно указать адрес нашего кластера Kafka и название целевой темы для канала. Адрес Kafka вводится на этапе развертывания.
spring.kafka.bootstrap-servers = ${KAFKA_URL}
spring.cloud.stream.bindings.transactionsSupplier-out-0.destination = transactions
Наконец, давайте развернем наш Spring Boot на Kubernetes. Вот манифест YAML, содержащий Kubernetes Deployment
и Service
определения:
apiVersion: apps/v1
kind: Deployment
metadata:
name: transactions
spec:
selector:
matchLabels:
app: transactions
template:
metadata:
labels:
app: transactions
spec:
containers:
- name: transactions
image: piomin/transactions-service
env:
- name: KAFKA_URL
value: my-cluster-kafka-bootstrap:9092
ports:
- containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
name: transactions
spec:
type: ClusterIP
selector:
app: transactions
ports:
- port: 8080
Давайте развернем приложение в kafka
пространстве имен:
$ kubectl apply -f k8s/deployment.yaml -n kafka
Как только приложение будет развернуто в Kubernetes, давайте включим его port-forward
для тестирования на локальном порту:
$ kubectl port-forward service/transactions 8080:8080
Теперь мы можем протестировать наши две конечные точки HTTP. Начнем с конечной точки для поиска всех транзакций:
$ curl http://localhost:8080/transactions
Затем вы можете вызвать конечную точку для поиска всех транзакций, связанных с targetAccountId
, например:
$ curl http://localhost:8080/transactions/target/10
В этой статье я хотел показать, как начать работу с ksqlDB в Kubernetes. Для взаимодействия с Kafka и ksqlDB мы использовали такие фреймворки, как Spring Boot и Spring Cloud Stream. Вы могли увидеть, как запустить кластер Kafka в Kubernetes с помощью оператора Strimzi или как развернуть KSQL Server прямо из репозитория Helm.
Ссылка: https://piotrminkowski.com/2022/06/22/introduction-to-ksqldb-on-kubernetes-with-spring-boot/
#springboot #spring #kubernetes #ksqlDB #java
1654075127
Amazon Aurora is a relational database management system (RDBMS) developed by AWS(Amazon Web Services). Aurora gives you the performance and availability of commercial-grade databases with full MySQL and PostgreSQL compatibility. In terms of high performance, Aurora MySQL and Aurora PostgreSQL have shown an increase in throughput of up to 5X over stock MySQL and 3X over stock PostgreSQL respectively on similar hardware. In terms of scalability, Aurora achieves enhancements and innovations in storage and computing, horizontal and vertical functions.
Aurora supports up to 128TB of storage capacity and supports dynamic scaling of storage layer in units of 10GB. In terms of computing, Aurora supports scalable configurations for multiple read replicas. Each region can have an additional 15 Aurora replicas. In addition, Aurora provides multi-primary architecture to support four read/write nodes. Its Serverless architecture allows vertical scaling and reduces typical latency to under a second, while the Global Database enables a single database cluster to span multiple AWS Regions in low latency.
Aurora already provides great scalability with the growth of user data volume. Can it handle more data and support more concurrent access? You may consider using sharding to support the configuration of multiple underlying Aurora clusters. To this end, a series of blogs, including this one, provides you with a reference in choosing between Proxy and JDBC for sharding.
AWS Aurora offers a single relational database. Primary-secondary, multi-primary, and global database, and other forms of hosting architecture can satisfy various architectural scenarios above. However, Aurora doesn’t provide direct support for sharding scenarios, and sharding has a variety of forms, such as vertical and horizontal forms. If we want to further increase data capacity, some problems have to be solved, such as cross-node database Join
, associated query, distributed transactions, SQL sorting, page turning, function calculation, database global primary key, capacity planning, and secondary capacity expansion after sharding.
It is generally accepted that when the capacity of a MySQL table is less than 10 million, the time spent on queries is optimal because at this time the height of its BTREE
index is between 3 and 5. Data sharding can reduce the amount of data in a single table and distribute the read and write loads to different data nodes at the same time. Data sharding can be divided into vertical sharding and horizontal sharding.
1. Advantages of vertical sharding
2. Disadvantages of vertical sharding
Join
can only be implemented by interface aggregation, which will increase the complexity of development.3. Advantages of horizontal sharding
4. Disadvantages of horizontal sharding
Join
is poor.Based on the analysis above, and the available studis on popular sharding middleware, we selected ShardingSphere, an open source product, combined with Amazon Aurora to introduce how the combination of these two products meets various forms of sharding and how to solve the problems brought by sharding.
ShardingSphere is an open source ecosystem including a set of distributed database middleware solutions, including 3 independent products, Sharding-JDBC, Sharding-Proxy & Sharding-Sidecar.
The characteristics of Sharding-JDBC are:
Hybrid Structure Integrating Sharding-JDBC and Applications
Sharding-JDBC’s core concepts
Data node: The smallest unit of a data slice, consisting of a data source name and a data table, such as ds_0.product_order_0.
Actual table: The physical table that really exists in the horizontal sharding database, such as product order tables: product_order_0, product_order_1, and product_order_2.
Logic table: The logical name of the horizontal sharding databases (tables) with the same schema. For instance, the logic table of the order product_order_0, product_order_1, and product_order_2 is product_order.
Binding table: It refers to the primary table and the joiner table with the same sharding rules. For example, product_order table and product_order_item are sharded by order_id, so they are binding tables with each other. Cartesian product correlation will not appear in the multi-tables correlating query, so the query efficiency will increase greatly.
Broadcast table: It refers to tables that exist in all sharding database sources. The schema and data must consist in each database. It can be applied to the small data volume that needs to correlate with big data tables to query, dictionary table and configuration table for example.
Download the example project code locally. In order to ensure the stability of the test code, we choose shardingsphere-example-4.0.0
version.
git clone
https://github.com/apache/shardingsphere-example.git
Project description:
shardingsphere-example
├── example-core
│ ├── config-utility
│ ├── example-api
│ ├── example-raw-jdbc
│ ├── example-spring-jpa #spring+jpa integration-based entity,repository
│ └── example-spring-mybatis
├── sharding-jdbc-example
│ ├── sharding-example
│ │ ├── sharding-raw-jdbc-example
│ │ ├── sharding-spring-boot-jpa-example #integration-based sharding-jdbc functions
│ │ ├── sharding-spring-boot-mybatis-example
│ │ ├── sharding-spring-namespace-jpa-example
│ │ └── sharding-spring-namespace-mybatis-example
│ ├── orchestration-example
│ │ ├── orchestration-raw-jdbc-example
│ │ ├── orchestration-spring-boot-example #integration-based sharding-jdbc governance function
│ │ └── orchestration-spring-namespace-example
│ ├── transaction-example
│ │ ├── transaction-2pc-xa-example #sharding-jdbc sample of two-phase commit for a distributed transaction
│ │ └──transaction-base-seata-example #sharding-jdbc distributed transaction seata sample
│ ├── other-feature-example
│ │ ├── hint-example
│ │ └── encrypt-example
├── sharding-proxy-example
│ └── sharding-proxy-boot-mybatis-example
└── src/resources
└── manual_schema.sql
Configuration file description:
application-master-slave.properties #read/write splitting profile
application-sharding-databases-tables.properties #sharding profile
application-sharding-databases.properties #library split profile only
application-sharding-master-slave.properties #sharding and read/write splitting profile
application-sharding-tables.properties #table split profile
application.properties #spring boot profile
Code logic description:
The following is the entry class of the Spring Boot application below. Execute it to run the project.
The execution logic of demo is as follows:
As business grows, the write and read requests can be split to different database nodes to effectively promote the processing capability of the entire database cluster. Aurora uses a reader/writer endpoint
to meet users' requirements to write and read with strong consistency, and a read-only endpoint
to meet the requirements to read without strong consistency. Aurora's read and write latency is within single-digit milliseconds, much lower than MySQL's binlog
-based logical replication, so there's a lot of loads that can be directed to a read-only endpoint
.
Through the one primary and multiple secondary configuration, query requests can be evenly distributed to multiple data replicas, which further improves the processing capability of the system. Read/write splitting can improve the throughput and availability of system, but it can also lead to data inconsistency. Aurora provides a primary/secondary architecture in a fully managed form, but applications on the upper-layer still need to manage multiple data sources when interacting with Aurora, routing SQL requests to different nodes based on the read/write type of SQL statements and certain routing policies.
ShardingSphere-JDBC provides read/write splitting features and it is integrated with application programs so that the complex configuration between application programs and database clusters can be separated from application programs. Developers can manage the Shard
through configuration files and combine it with ORM frameworks such as Spring JPA and Mybatis to completely separate the duplicated logic from the code, which greatly improves the ability to maintain code and reduces the coupling between code and database.
Create a set of Aurora MySQL read/write splitting clusters. The model is db.r5.2xlarge. Each set of clusters has one write node and two read nodes.
application.properties spring boot
Master profile description:
You need to replace the green ones with your own environment configuration.
# Jpa automatically creates and drops data tables based on entities
spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.show_sql=true
#spring.profiles.active=sharding-databases
#spring.profiles.active=sharding-tables
#spring.profiles.active=sharding-databases-tables
#Activate master-slave configuration item so that sharding-jdbc can use master-slave profile
spring.profiles.active=master-slave
#spring.profiles.active=sharding-master-slave
application-master-slave.properties sharding-jdbc
profile description:
spring.shardingsphere.datasource.names=ds_master,ds_slave_0,ds_slave_1
# data souce-master
spring.shardingsphere.datasource.ds_master.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds_master.password=Your master DB password
spring.shardingsphere.datasource.ds_master.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds_master.jdbc-url=Your primary DB data sourceurl spring.shardingsphere.datasource.ds_master.username=Your primary DB username
# data source-slave
spring.shardingsphere.datasource.ds_slave_0.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds_slave_0.password= Your slave DB password
spring.shardingsphere.datasource.ds_slave_0.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds_slave_0.jdbc-url=Your slave DB data source url
spring.shardingsphere.datasource.ds_slave_0.username= Your slave DB username
# data source-slave
spring.shardingsphere.datasource.ds_slave_1.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds_slave_1.password= Your slave DB password
spring.shardingsphere.datasource.ds_slave_1.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds_slave_1.jdbc-url= Your slave DB data source url
spring.shardingsphere.datasource.ds_slave_1.username= Your slave DB username
# Routing Policy Configuration
spring.shardingsphere.masterslave.load-balance-algorithm-type=round_robin
spring.shardingsphere.masterslave.name=ds_ms
spring.shardingsphere.masterslave.master-data-source-name=ds_master
spring.shardingsphere.masterslave.slave-data-source-names=ds_slave_0,ds_slave_1
# sharding-jdbc configures the information storage mode
spring.shardingsphere.mode.type=Memory
# start shardingsphere log,and you can see the conversion from logical SQL to actual SQL from the print
spring.shardingsphere.props.sql.show=true
As shown in the ShardingSphere-SQL log
figure below, the write SQL is executed on the ds_master
data source.
As shown in the ShardingSphere-SQL log
figure below, the read SQL is executed on the ds_slave
data source in the form of polling.
[INFO ] 2022-04-02 19:43:39,376 --main-- [ShardingSphere-SQL] Rule Type: master-slave
[INFO ] 2022-04-02 19:43:39,376 --main-- [ShardingSphere-SQL] SQL: select orderentit0_.order_id as order_id1_1_, orderentit0_.address_id as address_2_1_,
orderentit0_.status as status3_1_, orderentit0_.user_id as user_id4_1_ from t_order orderentit0_ ::: DataSources: ds_slave_0
---------------------------- Print OrderItem Data -------------------
Hibernate: select orderiteme1_.order_item_id as order_it1_2_, orderiteme1_.order_id as order_id2_2_, orderiteme1_.status as status3_2_, orderiteme1_.user_id
as user_id4_2_ from t_order orderentit0_ cross join t_order_item orderiteme1_ where orderentit0_.order_id=orderiteme1_.order_id
[INFO ] 2022-04-02 19:43:40,898 --main-- [ShardingSphere-SQL] Rule Type: master-slave
[INFO ] 2022-04-02 19:43:40,898 --main-- [ShardingSphere-SQL] SQL: select orderiteme1_.order_item_id as order_it1_2_, orderiteme1_.order_id as order_id2_2_, orderiteme1_.status as status3_2_,
orderiteme1_.user_id as user_id4_2_ from t_order orderentit0_ cross join t_order_item orderiteme1_ where orderentit0_.order_id=orderiteme1_.order_id ::: DataSources: ds_slave_1
Note: As shown in the figure below, if there are both reads and writes in a transaction, Sharding-JDBC routes both read and write operations to the master library. If the read/write requests are not in the same transaction, the corresponding read requests are distributed to different read nodes according to the routing policy.
@Override
@Transactional // When a transaction is started, both read and write in the transaction go through the master library. When closed, read goes through the slave library and write goes through the master library
public void processSuccess() throws SQLException {
System.out.println("-------------- Process Success Begin ---------------");
List<Long> orderIds = insertData();
printData();
deleteData(orderIds);
printData();
System.out.println("-------------- Process Success Finish --------------");
}
The Aurora database environment adopts the configuration described in Section 2.2.1.
3.2.4.1 Verification process description
Spring-Boot
project2. Perform a failover on Aurora’s console
3. Execute the Rest API
request
4. Repeatedly execute POST
(http://localhost:8088/save-user) until the call to the API failed to write to Aurora and eventually recovered successfully.
5. The following figure shows the process of executing code failover. It takes about 37 seconds from the time when the latest SQL write is successfully performed to the time when the next SQL write is successfully performed. That is, the application can be automatically recovered from Aurora failover, and the recovery time is about 37 seconds.
application.properties spring boot
master profile description
# Jpa automatically creates and drops data tables based on entities
spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.show_sql=true
#spring.profiles.active=sharding-databases
#Activate sharding-tables configuration items
#spring.profiles.active=sharding-tables
#spring.profiles.active=sharding-databases-tables
# spring.profiles.active=master-slave
#spring.profiles.active=sharding-master-slave
application-sharding-tables.properties sharding-jdbc
profile description
## configure primary-key policy
spring.shardingsphere.sharding.tables.t_order.key-generator.column=order_id
spring.shardingsphere.sharding.tables.t_order.key-generator.type=SNOWFLAKE
spring.shardingsphere.sharding.tables.t_order.key-generator.props.worker.id=123
spring.shardingsphere.sharding.tables.t_order_item.actual-data-nodes=ds.t_order_item_$->{0..1}
spring.shardingsphere.sharding.tables.t_order_item.table-strategy.inline.sharding-column=order_id
spring.shardingsphere.sharding.tables.t_order_item.table-strategy.inline.algorithm-expression=t_order_item_$->{order_id % 2}
spring.shardingsphere.sharding.tables.t_order_item.key-generator.column=order_item_id
spring.shardingsphere.sharding.tables.t_order_item.key-generator.type=SNOWFLAKE
spring.shardingsphere.sharding.tables.t_order_item.key-generator.props.worker.id=123
# configure the binding relation of t_order and t_order_item
spring.shardingsphere.sharding.binding-tables[0]=t_order,t_order_item
# configure broadcast tables
spring.shardingsphere.sharding.broadcast-tables=t_address
# sharding-jdbc mode
spring.shardingsphere.mode.type=Memory
# start shardingsphere log
spring.shardingsphere.props.sql.show=true
1. DDL operation
JPA automatically creates tables for testing. When Sharding-JDBC routing rules are configured, the client
executes DDL, and Sharding-JDBC automatically creates corresponding tables according to the table splitting rules. If t_address
is a broadcast table, create a t_address
because there is only one master instance. Two physical tables t_order_0
and t_order_1
will be created when creating t_order
.
2. Write operation
As shown in the figure below, Logic SQL
inserts a record into t_order
. When Sharding-JDBC is executed, data will be distributed to t_order_0
and t_order_1
according to the table splitting rules.
When t_order
and t_order_item
are bound, the records associated with order_item
and order
are placed on the same physical table.
3. Read operation
As shown in the figure below, perform the join
query operations to order
and order_item
under the binding table, and the physical shard is precisely located based on the binding relationship.
The join
query operations on order
and order_item
under the unbound table will traverse all shards.
Create two instances on Aurora: ds_0
and ds_1
When the sharding-spring-boot-jpa-example
project is started, tables t_order
, t_order_item
,t_address
will be created on two Aurora instances.
application.properties springboot
master profile description
# Jpa automatically creates and drops data tables based on entities
spring.jpa.properties.hibernate.hbm2ddl.auto=create
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.show_sql=true
# Activate sharding-databases configuration items
spring.profiles.active=sharding-databases
#spring.profiles.active=sharding-tables
#spring.profiles.active=sharding-databases-tables
#spring.profiles.active=master-slave
#spring.profiles.active=sharding-master-slave
application-sharding-databases.properties sharding-jdbc
profile description
spring.shardingsphere.datasource.names=ds_0,ds_1
# ds_0
spring.shardingsphere.datasource.ds_0.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds_0.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds_0.jdbc-url= spring.shardingsphere.datasource.ds_0.username=
spring.shardingsphere.datasource.ds_0.password=
# ds_1
spring.shardingsphere.datasource.ds_1.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds_1.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds_1.jdbc-url=
spring.shardingsphere.datasource.ds_1.username=
spring.shardingsphere.datasource.ds_1.password=
spring.shardingsphere.sharding.default-database-strategy.inline.sharding-column=user_id
spring.shardingsphere.sharding.default-database-strategy.inline.algorithm-expression=ds_$->{user_id % 2}
spring.shardingsphere.sharding.binding-tables=t_order,t_order_item
spring.shardingsphere.sharding.broadcast-tables=t_address
spring.shardingsphere.sharding.default-data-source-name=ds_0
spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=ds_$->{0..1}.t_order
spring.shardingsphere.sharding.tables.t_order.key-generator.column=order_id
spring.shardingsphere.sharding.tables.t_order.key-generator.type=SNOWFLAKE
spring.shardingsphere.sharding.tables.t_order.key-generator.props.worker.id=123
spring.shardingsphere.sharding.tables.t_order_item.actual-data-nodes=ds_$->{0..1}.t_order_item
spring.shardingsphere.sharding.tables.t_order_item.key-generator.column=order_item_id
spring.shardingsphere.sharding.tables.t_order_item.key-generator.type=SNOWFLAKE
spring.shardingsphere.sharding.tables.t_order_item.key-generator.props.worker.id=123
# sharding-jdbc mode
spring.shardingsphere.mode.type=Memory
# start shardingsphere log
spring.shardingsphere.props.sql.show=true
1. DDL operation
JPA automatically creates tables for testing. When Sharding-JDBC’s library splitting and routing rules are configured, the client
executes DDL, and Sharding-JDBC will automatically create corresponding tables according to table splitting rules. If t_address
is a broadcast table, physical tables will be created on ds_0
and ds_1
. The three tables, t_address
, t_order
and t_order_item
will be created on ds_0
and ds_1
respectively.
2. Write operation
For the broadcast table t_address
, each record written will also be written to the t_address
tables of ds_0
and ds_1
.
The tables t_order
and t_order_item
of the slave library are written on the table in the corresponding instance according to the slave library field and routing policy.
3. Read operation
Query order
is routed to the corresponding Aurora instance according to the routing rules of the slave library .
Query Address
. Since address
is a broadcast table, an instance of address
will be randomly selected and queried from the nodes used.
As shown in the figure below, perform the join
query operations to order
and order_item
under the binding table, and the physical shard is precisely located based on the binding relationship.
As shown in the figure below, create two instances on Aurora: ds_0
and ds_1
When the sharding-spring-boot-jpa-example
project is started, physical tables t_order_01
, t_order_02
, t_order_item_01
,and t_order_item_02
and global table t_address
will be created on two Aurora instances.
application.properties springboot
master profile description
# Jpa automatically creates and drops data tables based on entities
spring.jpa.properties.hibernate.hbm2ddl.auto=create
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.show_sql=true
# Activate sharding-databases-tables configuration items
#spring.profiles.active=sharding-databases
#spring.profiles.active=sharding-tables
spring.profiles.active=sharding-databases-tables
#spring.profiles.active=master-slave
#spring.profiles.active=sharding-master-slave
application-sharding-databases.properties sharding-jdbc
profile description
spring.shardingsphere.datasource.names=ds_0,ds_1
# ds_0
spring.shardingsphere.datasource.ds_0.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds_0.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds_0.jdbc-url= 306/dev?useSSL=false&characterEncoding=utf-8
spring.shardingsphere.datasource.ds_0.username=
spring.shardingsphere.datasource.ds_0.password=
spring.shardingsphere.datasource.ds_0.max-active=16
# ds_1
spring.shardingsphere.datasource.ds_1.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds_1.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds_1.jdbc-url=
spring.shardingsphere.datasource.ds_1.username=
spring.shardingsphere.datasource.ds_1.password=
spring.shardingsphere.datasource.ds_1.max-active=16
# default library splitting policy
spring.shardingsphere.sharding.default-database-strategy.inline.sharding-column=user_id
spring.shardingsphere.sharding.default-database-strategy.inline.algorithm-expression=ds_$->{user_id % 2}
spring.shardingsphere.sharding.binding-tables=t_order,t_order_item
spring.shardingsphere.sharding.broadcast-tables=t_address
# Tables that do not meet the library splitting policy are placed on ds_0
spring.shardingsphere.sharding.default-data-source-name=ds_0
# t_order table splitting policy
spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=ds_$->{0..1}.t_order_$->{0..1}
spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.sharding-column=order_id
spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.algorithm-expression=t_order_$->{order_id % 2}
spring.shardingsphere.sharding.tables.t_order.key-generator.column=order_id
spring.shardingsphere.sharding.tables.t_order.key-generator.type=SNOWFLAKE
spring.shardingsphere.sharding.tables.t_order.key-generator.props.worker.id=123
# t_order_item table splitting policy
spring.shardingsphere.sharding.tables.t_order_item.actual-data-nodes=ds_$->{0..1}.t_order_item_$->{0..1}
spring.shardingsphere.sharding.tables.t_order_item.table-strategy.inline.sharding-column=order_id
spring.shardingsphere.sharding.tables.t_order_item.table-strategy.inline.algorithm-expression=t_order_item_$->{order_id % 2}
spring.shardingsphere.sharding.tables.t_order_item.key-generator.column=order_item_id
spring.shardingsphere.sharding.tables.t_order_item.key-generator.type=SNOWFLAKE
spring.shardingsphere.sharding.tables.t_order_item.key-generator.props.worker.id=123
# sharding-jdbc mdoe
spring.shardingsphere.mode.type=Memory
# start shardingsphere log
spring.shardingsphere.props.sql.show=true
1. DDL operation
JPA automatically creates tables for testing. When Sharding-JDBC’s sharding and routing rules are configured, the client
executes DDL, and Sharding-JDBC will automatically create corresponding tables according to table splitting rules. If t_address
is a broadcast table, t_address
will be created on both ds_0
and ds_1
. The three tables, t_address
, t_order
and t_order_item
will be created on ds_0
and ds_1
respectively.
2. Write operation
For the broadcast table t_address
, each record written will also be written to the t_address
tables of ds_0
and ds_1
.
The tables t_order
and t_order_item
of the sub-library are written to the table on the corresponding instance according to the slave library field and routing policy.
3. Read operation
The read operation is similar to the library split function verification described in section2.4.3.
The following figure shows the physical table of the created database instance.
application.properties spring boot
master profile description
# Jpa automatically creates and drops data tables based on entities
spring.jpa.properties.hibernate.hbm2ddl.auto=create
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.show_sql=true
# activate sharding-databases-tables configuration items
#spring.profiles.active=sharding-databases
#spring.profiles.active=sharding-tables
#spring.profiles.active=sharding-databases-tables
#spring.profiles.active=master-slave
spring.profiles.active=sharding-master-slave
application-sharding-master-slave.properties sharding-jdbc
profile description
The url, name and password of the database need to be changed to your own database parameters.
spring.shardingsphere.datasource.names=ds_master_0,ds_master_1,ds_master_0_slave_0,ds_master_0_slave_1,ds_master_1_slave_0,ds_master_1_slave_1
spring.shardingsphere.datasource.ds_master_0.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds_master_0.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds_master_0.jdbc-url= spring.shardingsphere.datasource.ds_master_0.username=
spring.shardingsphere.datasource.ds_master_0.password=
spring.shardingsphere.datasource.ds_master_0.max-active=16
spring.shardingsphere.datasource.ds_master_0_slave_0.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds_master_0_slave_0.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds_master_0_slave_0.jdbc-url= spring.shardingsphere.datasource.ds_master_0_slave_0.username=
spring.shardingsphere.datasource.ds_master_0_slave_0.password=
spring.shardingsphere.datasource.ds_master_0_slave_0.max-active=16
spring.shardingsphere.datasource.ds_master_0_slave_1.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds_master_0_slave_1.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds_master_0_slave_1.jdbc-url= spring.shardingsphere.datasource.ds_master_0_slave_1.username=
spring.shardingsphere.datasource.ds_master_0_slave_1.password=
spring.shardingsphere.datasource.ds_master_0_slave_1.max-active=16
spring.shardingsphere.datasource.ds_master_1.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds_master_1.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds_master_1.jdbc-url=
spring.shardingsphere.datasource.ds_master_1.username=
spring.shardingsphere.datasource.ds_master_1.password=
spring.shardingsphere.datasource.ds_master_1.max-active=16
spring.shardingsphere.datasource.ds_master_1_slave_0.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds_master_1_slave_0.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds_master_1_slave_0.jdbc-url=
spring.shardingsphere.datasource.ds_master_1_slave_0.username=
spring.shardingsphere.datasource.ds_master_1_slave_0.password=
spring.shardingsphere.datasource.ds_master_1_slave_0.max-active=16
spring.shardingsphere.datasource.ds_master_1_slave_1.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds_master_1_slave_1.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds_master_1_slave_1.jdbc-url= spring.shardingsphere.datasource.ds_master_1_slave_1.username=admin
spring.shardingsphere.datasource.ds_master_1_slave_1.password=
spring.shardingsphere.datasource.ds_master_1_slave_1.max-active=16
spring.shardingsphere.sharding.default-database-strategy.inline.sharding-column=user_id
spring.shardingsphere.sharding.default-database-strategy.inline.algorithm-expression=ds_$->{user_id % 2}
spring.shardingsphere.sharding.binding-tables=t_order,t_order_item
spring.shardingsphere.sharding.broadcast-tables=t_address
spring.shardingsphere.sharding.default-data-source-name=ds_master_0
spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=ds_$->{0..1}.t_order_$->{0..1}
spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.sharding-column=order_id
spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.algorithm-expression=t_order_$->{order_id % 2}
spring.shardingsphere.sharding.tables.t_order.key-generator.column=order_id
spring.shardingsphere.sharding.tables.t_order.key-generator.type=SNOWFLAKE
spring.shardingsphere.sharding.tables.t_order.key-generator.props.worker.id=123
spring.shardingsphere.sharding.tables.t_order_item.actual-data-nodes=ds_$->{0..1}.t_order_item_$->{0..1}
spring.shardingsphere.sharding.tables.t_order_item.table-strategy.inline.sharding-column=order_id
spring.shardingsphere.sharding.tables.t_order_item.table-strategy.inline.algorithm-expression=t_order_item_$->{order_id % 2}
spring.shardingsphere.sharding.tables.t_order_item.key-generator.column=order_item_id
spring.shardingsphere.sharding.tables.t_order_item.key-generator.type=SNOWFLAKE
spring.shardingsphere.sharding.tables.t_order_item.key-generator.props.worker.id=123
# master/slave data source and slave data source configuration
spring.shardingsphere.sharding.master-slave-rules.ds_0.master-data-source-name=ds_master_0
spring.shardingsphere.sharding.master-slave-rules.ds_0.slave-data-source-names=ds_master_0_slave_0, ds_master_0_slave_1
spring.shardingsphere.sharding.master-slave-rules.ds_1.master-data-source-name=ds_master_1
spring.shardingsphere.sharding.master-slave-rules.ds_1.slave-data-source-names=ds_master_1_slave_0, ds_master_1_slave_1
# sharding-jdbc mode
spring.shardingsphere.mode.type=Memory
# start shardingsphere log
spring.shardingsphere.props.sql.show=true
1. DDL operation
JPA automatically creates tables for testing. When Sharding-JDBC’s library splitting and routing rules are configured, the client
executes DDL, and Sharding-JDBC will automatically create corresponding tables according to table splitting rules. If t_address
is a broadcast table, t_address
will be created on both ds_0
and ds_1
. The three tables, t_address
, t_order
and t_order_item
will be created on ds_0
and ds_1
respectively.
2. Write operation
For the broadcast table t_address
, each record written will also be written to the t_address
tables of ds_0
and ds_1
.
The tables t_order
and t_order_item
of the slave library are written to the table on the corresponding instance according to the slave library field and routing policy.
3. Read operation
The join
query operations on order
and order_item
under the binding table are shown below.
3. Conclusion
As an open source product focusing on database enhancement, ShardingSphere is pretty good in terms of its community activitiy, product maturity and documentation richness.
Among its products, ShardingSphere-JDBC is a sharding solution based on the client-side, which supports all sharding scenarios. And there’s no need to introduce an intermediate layer like Proxy, so the complexity of operation and maintenance is reduced. Its latency is theoretically lower than Proxy due to the lack of intermediate layer. In addition, ShardingSphere-JDBC can support a variety of relational databases based on SQL standards such as MySQL/PostgreSQL/Oracle/SQL Server, etc.
However, due to the integration of Sharding-JDBC with the application program, it only supports Java language for now, and is strongly dependent on the application programs. Nevertheless, Sharding-JDBC separates all sharding configuration from the application program, which brings relatively small changes when switching to other middleware.
In conclusion, Sharding-JDBC is a good choice if you use a Java-based system and have to to interconnect with different relational databases — and don’t want to bother with introducing an intermediate layer.
Author
Sun Jinhua
A senior solution architect at AWS, Sun is responsible for the design and consult on cloud architecture. for providing customers with cloud-related design and consulting services. Before joining AWS, he ran his own business, specializing in building e-commerce platforms and designing the overall architecture for e-commerce platforms of automotive companies. He worked in a global leading communication equipment company as a senior engineer, responsible for the development and architecture design of multiple subsystems of LTE equipment system. He has rich experience in architecture design with high concurrency and high availability system, microservice architecture design, database, middleware, IOT etc.
1602964260
Last year, we provided a list of Kubernetes tools that proved so popular we have decided to curate another list of some useful additions for working with the platform—among which are many tools that we personally use here at Caylent. Check out the original tools list here in case you missed it.
According to a recent survey done by Stackrox, the dominance Kubernetes enjoys in the market continues to be reinforced, with 86% of respondents using it for container orchestration.
(State of Kubernetes and Container Security, 2020)
And as you can see below, more and more companies are jumping into containerization for their apps. If you’re among them, here are some tools to aid you going forward as Kubernetes continues its rapid growth.
(State of Kubernetes and Container Security, 2020)
#blog #tools #amazon elastic kubernetes service #application security #aws kms #botkube #caylent #cli #container monitoring #container orchestration tools #container security #containers #continuous delivery #continuous deployment #continuous integration #contour #developers #development #developments #draft #eksctl #firewall #gcp #github #harbor #helm #helm charts #helm-2to3 #helm-aws-secret-plugin #helm-docs #helm-operator-get-started #helm-secrets #iam #json #k-rail #k3s #k3sup #k8s #keel.sh #keycloak #kiali #kiam #klum #knative #krew #ksniff #kube #kube-prod-runtime #kube-ps1 #kube-scan #kube-state-metrics #kube2iam #kubeapps #kubebuilder #kubeconfig #kubectl #kubectl-aws-secrets #kubefwd #kubernetes #kubernetes command line tool #kubernetes configuration #kubernetes deployment #kubernetes in development #kubernetes in production #kubernetes ingress #kubernetes interfaces #kubernetes monitoring #kubernetes networking #kubernetes observability #kubernetes plugins #kubernetes secrets #kubernetes security #kubernetes security best practices #kubernetes security vendors #kubernetes service discovery #kubernetic #kubesec #kubeterminal #kubeval #kudo #kuma #microsoft azure key vault #mozilla sops #octant #octarine #open source #palo alto kubernetes security #permission-manager #pgp #rafay #rakess #rancher #rook #secrets operations #serverless function #service mesh #shell-operator #snyk #snyk container #sonobuoy #strongdm #tcpdump #tenkai #testing #tigera #tilt #vert.x #wireshark #yaml
1658817167
В этой статье вы узнаете, как запустить ksqlDB в Kubernetes и использовать его с Spring Boot. Вы также увидите, как запустить Kafka в Kubernetes на основе оператора Strimzi . Чтобы интегрировать Spring Boot с сервером ksqlDB, мы собираемся использовать облегченный Java-клиент, предоставляемый ksqlDB. Этот клиент поддерживает запросы pull и push. Он также предоставляет API для вставки строк и создания таблиц или потоков. Подробнее об этом можно прочитать в документации ksqlDB здесь .
Наш образец приложения Spring Boot очень прост. Мы будем использовать Supplier
bean-компонент Spring Cloud Stream для генерации и отправки событий в тему Kafka. Дополнительные сведения о Kafka с Spring Cloud Stream см. в следующей статье . С другой стороны, наше приложение получает данные из темы Kafka с помощью запросов kSQL. Он также создается KTable
при запуске.
Давайте посмотрим на нашу архитектуру.
Если вы хотите попробовать это самостоятельно, вы всегда можете взглянуть на мой исходный код. Для этого вам нужно клонировать мой репозиторий GitHub . Затем перейдите в transactions-service
каталог. После этого вы должны просто следовать моим инструкциям. Давайте начнем.
Мы будем использовать несколько инструментов. Тебе нужно иметь:
kubectl
CLI — для взаимодействия с кластеромКонечно, нам нужен экземпляр Kafka для выполнения нашего упражнения. Есть несколько способов запустить Kafka в Kubernetes. Я покажу вам, как это сделать с помощью оператора. На первом этапе вам необходимо установить OLM (диспетчер жизненного цикла оператора) в вашем кластере. Для этого вы можете просто выполнить следующую команду в своем контексте Kubernetes:
$ curl -L https://github.com/operator-framework/operator-lifecycle-manager/releases/download/v0.21.2/install.sh -o install.sh
$ chmod +x install.sh
$ ./install.sh v0.21.2
Затем можно переходить к установке оператора Strimzi. Это всего лишь одна команда.
$ kubectl create -f https://operatorhub.io/install/stable/strimzi-kafka-operator.yaml
Теперь мы можем создать кластер Kafka в Kubernetes. Давайте начнем с выделенного пространства имен для нашего упражнения:
$ kubectl create ns kafka
Я предполагаю, что у вас есть кластер Kubernetes с одним узлом, поэтому мы также создадим Kafka с одним узлом. Вот манифест YAML с Kafka
CRD. Вы можете найти его в репозитории по пути k8s/cluster.yaml
.
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
entityOperator:
topicOperator: {}
userOperator: {}
kafka:
config:
default.replication.factor: 1
inter.broker.protocol.version: "3.2"
min.insync.replicas: 1
offsets.topic.replication.factor: 1
transaction.state.log.min.isr: 1
transaction.state.log.replication.factor: 1
listeners:
- name: plain
port: 9092
tls: false
type: internal
- name: tls
port: 9093
tls: true
type: internal
replicas: 1
storage:
type: jbod
volumes:
- id: 0
type: persistent-claim
size: 30Gi
deleteClaim: true
version: 3.2.0
zookeeper:
replicas: 1
storage:
type: persistent-claim
size: 10Gi
deleteClaim: true
Давайте применим его к Kubernetes в kafka
пространстве имен:
$ kubectl apply -f k8s/cluster.yaml -n kafka
Вы должны увидеть один экземпляр Kafka, а также один экземпляр Zookeeper. Если модули работают, значит, у вас есть Kafka в Kubernetes.
$ kubectl get pod -n kafka
NAME READY STATUS RESTARTS AGE
my-cluster-entity-operator-68cc6bc4d9-qs88p 3/3 Running 0 46m
my-cluster-kafka-0 1/1 Running 0 48m
my-cluster-zookeeper-0 1/1 Running 0 48m
Kafka доступна внутри кластера под именем my-cluster-kafka-bootstrap
и портом 9092
.
kubectl get svc -n kafka
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
my-cluster-kafka-bootstrap ClusterIP 10.108.109.255 <none> 9091/TCP,9092/TCP,9093/TCP 47m
my-cluster-kafka-brokers ClusterIP None <none> 9090/TCP,9091/TCP,9092/TCP,9093/TCP 47m
my-cluster-zookeeper-client ClusterIP 10.102.10.251 <none> 2181/TCP 47m
my-cluster-zookeeper-nodes ClusterIP None <none> 2181/TCP,2888/TCP,3888/TCP 47m
Сервер KsqlDB является частью Confluent Platform. Поскольку мы устанавливаем не всю платформу Confluent на Kubernetes, а только кластер Kafka с открытым исходным кодом, нам нужно установить KsqlDB Server отдельно. Давайте сделаем это с Хелмом. Для сервера KSQL нет «официальной» диаграммы Helm. Поэтому нам следует сразу перейти к репозиторию Confluent Helm на GitHub:
$ git clone https://github.com/confluentinc/cp-helm-charts.git
$ cd cp-helm-charts
В этом репозитории вы можете найти отдельные диаграммы Helm для каждого отдельного компонента Confluent, включая, например, центр управления или KSQL Server. Расположение нашей диаграммы внутри репозитория — charts/cp-ksql-server
. Нам нужно переопределить некоторые настройки по умолчанию во время установки. Прежде всего, мы должны отключить безголовый режим. В автономном режиме KSQL Server не предоставляет конечную точку HTTP и загружает запросы из входного скрипта. Наше приложение Spring Boot будет подключаться к серверу через HTTP. На следующем шаге мы должны переопределить адрес кластера Kafka по умолчанию и версию KSQL Server по умолчанию, которая все еще 6.1.0
существует. Мы будем использовать последнюю версию 7.1.1
. Вот helm
команда, которую вы должны запустить в своем кластере Kubernetes:
$ helm install cp-ksql-server \
--set ksql.headless=false \
--set kafka.bootstrapServers=my-cluster-kafka-bootstrap:9092 \
--set imageTag=7.1.1 \
charts/cp-ksql-server -n kafka
Вот результат:
Давайте проверим, работает ли KSQL в кластере:
$ kubectl get pod -n kafka | grep ksql
cp-ksql-server-679fc98889-hldfv 2/2 Running 0 2m11s
Конечная точка HTTP доступна для других приложений под именем cp-ksql-server
и портом 8088
:
$ kubectl get svc -n kafka | grep ksql
cp-ksql-server ClusterIP 10.109.189.36 <none> 8088/TCP,5556/TCP 3m25s
Теперь у нас есть весь необходимый персонал, работающий в нашем кластере Kubernetes. Поэтому мы можем перейти к реализации приложения Spring Boot.
Готовой интеграции между Spring Boot и ksqlDB я не нашел. Поэтому будем использовать ksqldb-api-client
напрямую. В первом нам нужно включить репозиторий ksqlDB Maven и некоторые зависимости:
<dependencies>
...
<dependency>
<groupId>io.confluent.ksql</groupId>
<artifactId>ksqldb-api-client</artifactId>
<version>0.26.0</version>
</dependency>
<dependency>
<groupId>io.confluent.ksql</groupId>
<artifactId>ksqldb-udf</artifactId>
<version>0.26.0</version>
</dependency>
<dependency>
<groupId>io.confluent.ksql</groupId>
<artifactId>ksqldb-common</artifactId>
<version>0.26.0</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>ksqlDB</id>
<name>ksqlDB</name>
<url>https://ksqldb-maven.s3.amazonaws.com/maven/</url>
</repository>
</repositories>
После этого мы можем определить Spring, @Bean
возвращающий реализацию ksqlDB Client
. Поскольку мы будем запускать наше приложение в том же пространстве имен, что и KSQL Server, нам нужно указать имя службы Kubernetes в качестве имени хоста.
@Configuration
public class KSQLClientProducer {
@Bean
Client ksqlClient() {
ClientOptions options = ClientOptions.create()
.setHost("cp-ksql-server")
.setPort(8088);
return Client.create(options);
}
}
Наше приложение взаимодействует с KSQL Server через конечную точку HTTP. Он создает сингл KTable
при запуске. Для этого нам нужно вызвать executeStatement
метод для экземпляра компонента KSQL Client
. Мы создаем таблицу SOURCE, чтобы разрешить запуск запросов на включение в нее. Таблица получает данные из transactions
топика. Он ожидает формат JSON во входящих событиях.
public class KTableCreateListener implements ApplicationListener<ContextRefreshedEvent> {
private static final Logger LOG = LoggerFactory.getLogger(KTableCreateListener.class);
private Client ksqlClient;
public KTableCreateListener(Client ksqlClient) {
this.ksqlClient = ksqlClient;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
try {
String sql = """
CREATE SOURCE TABLE IF NOT EXISTS transactions_view (
id BIGINT PRIMARY KEY,
sourceAccountId BIGINT,
targetAccountId BIGINT,
amount INT
) WITH (
kafka_topic='transactions',
value_format='JSON'
);
""";
ExecuteStatementResult result = ksqlClient.executeStatement(sql).get();
LOG.info("Result: {}", result.queryId().orElse(null));
} catch (ExecutionException | InterruptedException e) {
LOG.error("Error: ", e);
}
}
}
После создания таблицы мы можем выполнить к ней несколько запросов. Есть довольно простые запросы. Мы пытаемся найти все транзакции и все транзакции, связанные с конкретной учетной записью.
@RestController
@RequestMapping("/transactions")
public class TransactionResource {
private static final Logger LOG = LoggerFactory.getLogger(TransactionResource.class);
Client ksqlClient;
public TransactionResource(Client ksqlClient) {
this.ksqlClient = ksqlClient;
}
@GetMapping
public List<Transaction> getTransactions() throws ExecutionException, InterruptedException {
StreamedQueryResult sqr = ksqlClient
.streamQuery("SELECT * FROM transactions_view;")
.get();
Row row;
List<Transaction> l = new ArrayList<>();
while ((row = sqr.poll()) != null) {
l.add(mapRowToTransaction(row));
}
return l;
}
@GetMapping("/target/{accountId}")
public List<Transaction> getTransactionsByTargetAccountId(@PathVariable("accountId") Long accountId)
throws ExecutionException, InterruptedException {
StreamedQueryResult sqr = ksqlClient
.streamQuery("SELECT * FROM transactions_view WHERE sourceAccountId=" + accountId + ";")
.get();
Row row;
List<Transaction> l = new ArrayList<>();
while ((row = sqr.poll()) != null) {
l.add(mapRowToTransaction(row));
}
return l;
}
private Transaction mapRowToTransaction(Row row) {
Transaction t = new Transaction();
t.setId(row.getLong("ID"));
t.setSourceAccountId(row.getLong("SOURCEACCOUNTID"));
t.setTargetAccountId(row.getLong("TARGETACCOUNTID"));
t.setAmount(row.getInteger("AMOUNT"));
return t;
}
}
Наконец, мы можем перейти к последней части нашего упражнения. Нам нужно сгенерировать тестовые данные и отправить их в transactions
топик Kafka. Самый простой способ добиться этого — с помощью модуля Spring Cloud Stream Kafka. Во-первых, давайте добавим следующую зависимость Maven:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-kafka</artifactId>
</dependency>
Затем мы можем создать производителя на основе Supplier
bean-компонента Spring. Бин Supplier
постоянно генерирует и отправляет новые события в целевой канал. По умолчанию действие повторяется раз в секунду.
@Configuration
public class KafkaEventProducer {
private static long transactionId = 0;
private static final Random r = new Random();
@Bean
public Supplier<Message<Transaction>> transactionsSupplier() {
return () -> {
Transaction t = new Transaction();
t.setId(++transactionId);
t.setSourceAccountId(r.nextLong(1, 100));
t.setTargetAccountId(r.nextLong(1, 100));
t.setAmount(r.nextInt(1, 10000));
Message<Transaction> o = MessageBuilder
.withPayload(t)
.setHeader(KafkaHeaders.MESSAGE_KEY, new TransactionKey(t.getId()))
.build();
return o;
};
}
}
Конечно, нам также нужно указать адрес нашего кластера Kafka и название целевой темы для канала. Адрес Kafka вводится на этапе развертывания.
spring.kafka.bootstrap-servers = ${KAFKA_URL}
spring.cloud.stream.bindings.transactionsSupplier-out-0.destination = transactions
Наконец, давайте развернем наш Spring Boot на Kubernetes. Вот манифест YAML, содержащий Kubernetes Deployment
и Service
определения:
apiVersion: apps/v1
kind: Deployment
metadata:
name: transactions
spec:
selector:
matchLabels:
app: transactions
template:
metadata:
labels:
app: transactions
spec:
containers:
- name: transactions
image: piomin/transactions-service
env:
- name: KAFKA_URL
value: my-cluster-kafka-bootstrap:9092
ports:
- containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
name: transactions
spec:
type: ClusterIP
selector:
app: transactions
ports:
- port: 8080
Давайте развернем приложение в kafka
пространстве имен:
$ kubectl apply -f k8s/deployment.yaml -n kafka
Как только приложение будет развернуто в Kubernetes, давайте включим его port-forward
для тестирования на локальном порту:
$ kubectl port-forward service/transactions 8080:8080
Теперь мы можем протестировать наши две конечные точки HTTP. Начнем с конечной точки для поиска всех транзакций:
$ curl http://localhost:8080/transactions
Затем вы можете вызвать конечную точку для поиска всех транзакций, связанных с targetAccountId
, например:
$ curl http://localhost:8080/transactions/target/10
В этой статье я хотел показать, как начать работу с ksqlDB в Kubernetes. Для взаимодействия с Kafka и ksqlDB мы использовали такие фреймворки, как Spring Boot и Spring Cloud Stream. Вы могли увидеть, как запустить кластер Kafka в Kubernetes с помощью оператора Strimzi или как развернуть KSQL Server прямо из репозитория Helm.
Ссылка: https://piotrminkowski.com/2022/06/22/introduction-to-ksqldb-on-kubernetes-with-spring-boot/
#springboot #spring #kubernetes #ksqlDB #java
1604402893
#spring #spring-framework #spring-boot #docker #devops #kubernetes
1620751200
#spring boot #spring boot tutorial #interceptor #interceptors #spring boot interceptor #spring boot tutorial for beginners