提交 3b4e44b3 编写于 作者: T tristaZero

rm -rf

上级 cc34f160
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
# ShardingSphere-example
ShardingSphere example.
Example for 1.x please see tags in `https://github.com/apache/incubator-shardingsphere/tree/${tag}/sharding-jdbc-example`
Example for 2.x or 3.x please see tags in `https://github.com/apache/incubator-shardingsphere-example/tree/${tag}`
Please do not use `dev` branch to run your example, example of `dev` branch is not released yet.
The manual schema initial script is in `https://github.com/apache/incubator-shardingsphere-example/blob/dev/src/resources/manual_schema.sql`,
please execute it before you first run the example.
Please make sure master-slave data sync on MySQL is running correctly. Otherwise this example will query empty data from slave.
## Using docker-compose to config startup environment
before we use docker compose, please install docker first : https://docs.docker.com/compose/install/
#### sharding-jdbc
1. access the docker folder (cd docker/sharding-jdbc/sharding)
2. launch the environment by docker compose (docker-compose up -d)
3. access mysql / etcd / zookeeper as you want
4. if there is conflict on port, just modify the mapper port in docker-compose.yml and then launch docker compose again(docker-compose up -d)
5. if you want to stop these environment, use command docker-compose down
#### sharding-proxy
1. access the docker folder (cd docker/sharding-proxy/sharding)
2. launch the environment by docker compose (docker-compose up -d)
3. access proxy by `mysql -h127.0.0.1 -P13308 -proot -uroot`
4. if there is conflict on port, just modify the mapper port in docker-compose.yml and then launch docker compose again(docker-compose up -d)
5. if you want to stop these environment, use command docker-compose down
to clean the docker container , you could use docker rm `docker ps -a -q` (be careful)
## sharding-sphere-example module design
### project module
```
sharding-sphere-example
├── example-common
│   ├── config-utility
│   ├── repository-api
│   ├── repository-jdbc
│   ├── repository-jpa
│   └── repository-mybatis
├── sharding-jdbc-example
│   ├── orchestration-example
│   │   ├── orchestration-raw-jdbc-example
│   │   ├── orchestration-spring-boot-example
│   │   └── orchestration-spring-namespace-example
│   ├── sharding-example
│   │   ├── sharding-raw-jdbc-example
│   │   ├── sharding-spring-boot-jpa-example
│   │   ├── sharding-spring-boot-mybatis-example
│   │   ├── sharding-spring-namespace-jpa-example
│   │   └── sharding-spring-namespace-mybatis-example
│   └── transaction-example
│   ├── transaction-2pc-xa-example
│   └── transaction-base-saga-example
├── sharding-proxy-example
│   └── sharding-proxy-boot-mybatis-example
└── src/resources
  └── manual_schema.sql
```
### Best practice for sharding data
* sharding databases
* sharding tables
* sharding databases and tables
* master-slave
* sharding & master-slave
you can get more detail from **[sharding-example](./sharding-jdbc-example/sharding-example)**
### Best practice for sharding + orchestration
* local zookeeper/etcd & sharding
local sharding configuration can override the configuration of zookeeper/etcd.
* cloud zookeeper/etcd & sharding
shardingsphere will load the sharding configuration form zookeeper/etcd directly.
you can get more detail from **[orchestration-example](./sharding-jdbc-example/orchestration-example)**
### Best Practice for sharding + distribution-transaction
* 2pc-xa transaction
* base-saga transaction
you can get more detail from **[transaction-example](./sharding-jdbc-example/transaction-example)**
### how to use hint routing
we will add hint example recently.
### how to config none-sharding tables
we will add none-sharding example recently.
### how to config broadcast-table
we will add broadcast-table example recently.
### how to use APM with shardingsphere
we will add APM example recently.
### how to encrypt & decrypt data in shardingsphere
we prefer to add encrypt & decrypt example recently.
### how to use sharding-proxy with jdbc.
we prefer to add a docker base example recently.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.repository.jdbc.repository;
import io.shardingsphere.example.repository.api.entity.OrderEncrypt;
import io.shardingsphere.example.repository.api.repository.OrderEncryptRepository;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
public abstract class BaseOrderEncryptRepository implements OrderEncryptRepository {
protected static final String SQL_INSERT_T_ORDER_ENCRYPT = "INSERT INTO t_order_encrypt (order_id, user_id, encrypt_id) VALUES (?, ?, ?)";
protected static final String SQL_DELETE_BY_ENCRYPT_ID = "DELETE FROM t_order_encrypt WHERE encrypt_id=?";
protected static final String SQL_UPDATE_BY_ENCRYPT_ID = "UPDATE t_order_encrypt SET encrypt_id = 11 WHERE encrypt_id=?";
private static final String SQL_CREATE_T_ORDER_ENCRYPT = "CREATE TABLE IF NOT EXISTS t_order_encrypt "
+ "(order_id BIGINT NOT NULL, user_id INT NOT NULL, encrypt_id VARCHAR(200), query_id VARCHAR(200), PRIMARY KEY (order_id))";
private static final String SQL_DROP_T_ORDER_ENCRYPT = "DROP TABLE IF EXISTS t_order_encrypt";
private static final String SQL_TRUNCATE_T_ORDER_ENCRYPT = "TRUNCATE TABLE t_order_encrypt";
private static final String SQL_SELECT_T_ORDER_ENCRYPT_ALL = "SELECT e.* FROM t_order o, t_order_encrypt e WHERE o.order_id = e.order_id";
private static final String SQL_SELECT_T_ORDER_ENCRYPT_RANGE = "SELECT e.* FROM t_order o, t_order_encrypt e WHERE o.order_id = e.order_id AND o.user_id BETWEEN 1 AND 5";
protected final void createEncryptTableNotExist(final Statement statement) throws SQLException {
statement.executeUpdate(SQL_CREATE_T_ORDER_ENCRYPT);
}
protected final void dropEncryptTable(final Statement statement) throws SQLException {
statement.executeUpdate(SQL_DROP_T_ORDER_ENCRYPT);
}
protected final void truncateEncryptTable(final Statement statement) throws SQLException {
statement.executeUpdate(SQL_TRUNCATE_T_ORDER_ENCRYPT);
}
protected final void insertEncrypt(final PreparedStatement preparedStatement, final OrderEncrypt orderEncrypt) throws SQLException {
preparedStatement.setLong(1, orderEncrypt.getOrderId());
preparedStatement.setInt(2, orderEncrypt.getUserId());
preparedStatement.setString(3, orderEncrypt.getEncryptId());
preparedStatement.executeUpdate();
try (ResultSet resultSet = preparedStatement.getGeneratedKeys()) {
if (resultSet.next()) {
orderEncrypt.setOrderId(resultSet.getLong(1));
}
}
}
protected final void deleteById(final PreparedStatement preparedStatement, final String encryptId) throws SQLException {
preparedStatement.setString(1, encryptId);
preparedStatement.executeUpdate();
}
protected final void updateById(final PreparedStatement preparedStatement, final String encryptId) throws SQLException {
preparedStatement.setString(1, encryptId);
preparedStatement.executeUpdate();
}
protected final List<OrderEncrypt> queryOrderEncrypt(final PreparedStatement preparedStatement) {
List<OrderEncrypt> result = new LinkedList<>();
try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
OrderEncrypt orderEncrypt = new OrderEncrypt();
orderEncrypt.setOrderId(resultSet.getLong(1));
orderEncrypt.setUserId(resultSet.getInt(2));
orderEncrypt.setEncryptId(resultSet.getString(3));
orderEncrypt.setQueryId(resultSet.getString(4));
result.add(orderEncrypt);
}
} catch (final SQLException ignored) {
}
return result;
}
@Override
public final List<OrderEncrypt> selectAll() {
return getOrderEncrypts(SQL_SELECT_T_ORDER_ENCRYPT_ALL);
}
@Override
public final List<OrderEncrypt> selectRange() {
return getOrderEncrypts(SQL_SELECT_T_ORDER_ENCRYPT_RANGE);
}
public abstract List<OrderEncrypt> getOrderEncrypts(String sql);
}
/*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package io.shardingsphere.example.repository.jdbc.repository;
import io.shardingsphere.example.repository.api.entity.OrderEncrypt;
import io.shardingsphere.example.repository.api.repository.OrderEncryptRepository;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
public final class JDBCOrderEncryptRepositoryImpl extends BaseOrderEncryptRepository implements OrderEncryptRepository {
private final DataSource dataSource;
public JDBCOrderEncryptRepositoryImpl(final DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void createTableIfNotExists() {
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
createEncryptTableNotExist(statement);
} catch (final SQLException ignored) {
}
}
@Override
public void dropTable() {
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
dropEncryptTable(statement);
} catch (final SQLException ignored) {
}
}
@Override
public void truncateTable() {
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
truncateEncryptTable(statement);
} catch (final SQLException ignored) {
}
}
@Override
public Long insert(final OrderEncrypt orderEncrypt) {
try (Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(SQL_INSERT_T_ORDER_ENCRYPT, Statement.RETURN_GENERATED_KEYS)) {
insertEncrypt(preparedStatement, orderEncrypt);
} catch (final SQLException ignored) {
}
return orderEncrypt.getOrderId();
}
@Override
public void delete(final Long encryptId) {
try (Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(SQL_DELETE_BY_ENCRYPT_ID)) {
deleteById(preparedStatement, encryptId.toString());
} catch (final SQLException ignored) {
}
}
@Override
public void update(final String encryptId) {
try (Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(SQL_UPDATE_BY_ENCRYPT_ID)) {
updateById(preparedStatement, encryptId);
} catch (final SQLException ignored) {
}
}
@Override
public List<OrderEncrypt> getOrderEncrypts(final String sql) {
List<OrderEncrypt> result = new LinkedList<>();
try (Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
result = queryOrderEncrypt(preparedStatement);
} catch (final SQLException ignored) {
}
return result;
}
}
/*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package io.shardingsphere.example.repository.jdbc.repository;
import io.shardingsphere.example.repository.api.entity.OrderEncrypt;
import io.shardingsphere.example.repository.api.repository.OrderEncryptRepository;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
public final class JDBCOrderEncryptTransactionRepositoryImpl extends BaseOrderEncryptRepository implements OrderEncryptRepository {
private Connection connection;
public JDBCOrderEncryptTransactionRepositoryImpl(final Connection connection) {
this.connection = connection;
}
public void setConnection(final Connection connection) {
this.connection = connection;
}
@Override
public void createTableIfNotExists() {
try (Statement statement = connection.createStatement()) {
createEncryptTableNotExist(statement);
} catch (final SQLException ignored) {
}
}
@Override
public void dropTable() {
try (Statement statement = connection.createStatement()) {
dropEncryptTable(statement);
} catch (final SQLException ignored) {
}
}
@Override
public void truncateTable() {
try (Statement statement = connection.createStatement()) {
truncateEncryptTable(statement);
} catch (final SQLException ignored) {
}
}
@Override
public Long insert(final OrderEncrypt orderEncrypt) {
try (PreparedStatement preparedStatement = connection.prepareStatement(SQL_INSERT_T_ORDER_ENCRYPT, Statement.RETURN_GENERATED_KEYS)) {
insertEncrypt(preparedStatement, orderEncrypt);
} catch (final SQLException ignored) {
}
return orderEncrypt.getOrderId();
}
@Override
public void delete(final Long encryptId) {
try (PreparedStatement preparedStatement = connection.prepareStatement(SQL_DELETE_BY_ENCRYPT_ID)) {
deleteById(preparedStatement, encryptId.toString());
} catch (final SQLException ignored) {
}
}
@Override
public void update(final String encryptId) {
try (PreparedStatement preparedStatement = connection.prepareStatement(SQL_UPDATE_BY_ENCRYPT_ID)) {
updateById(preparedStatement, encryptId);
} catch (final SQLException ignored) {
}
}
@Override
public List<OrderEncrypt> getOrderEncrypts(final String sql) {
List<OrderEncrypt> result = new LinkedList<>();
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
result = queryOrderEncrypt(preparedStatement);
} catch (final SQLException ignored) {
}
return result;
}
}
/*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package io.shardingsphere.example.repository.jpa.entity;
import io.shardingsphere.example.repository.api.entity.OrderEncrypt;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "t_order_encrypt")
public final class OrderEncryptEntity extends OrderEncrypt {
@Id
@Column(name = "order_id")
@Override
public long getOrderId() {
return super.getOrderId();
}
@Column(name = "user_id")
@Override
public int getUserId() {
return super.getUserId();
}
@Column(name = "encrypt_id")
@Override
public String getEncryptId() {
return super.getEncryptId();
}
@Column(name = "query_id")
@Override
public String getQueryId() {
return super.getQueryId();
}
}
/*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package io.shardingsphere.example.repository.jpa.repository;
import io.shardingsphere.example.repository.api.entity.OrderEncrypt;
import io.shardingsphere.example.repository.api.repository.OrderEncryptRepository;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.util.List;
@Repository
@Transactional
public class JPAOrderEncryptRepositoryImpl implements OrderEncryptRepository {
@PersistenceContext
private EntityManager entityManager;
@Override
public void createTableIfNotExists() {
throw new UnsupportedOperationException("createTableIfNotExists for JPA");
}
@Override
public void truncateTable() {
throw new UnsupportedOperationException("truncateTable for JPA");
}
@Override
public void dropTable() {
throw new UnsupportedOperationException("dropTable for JPA");
}
@Override
public Long insert(final OrderEncrypt orderEncrypt) {
Query query = entityManager.createNativeQuery("INSERT INTO t_order_encrypt (order_id, user_id, encrypt_id) VALUES (?, ?, ?)");
query.setParameter(1, orderEncrypt.getOrderId());
query.setParameter(2, orderEncrypt.getUserId());
query.setParameter(3, orderEncrypt.getEncryptId());
query.executeUpdate();
return orderEncrypt.getOrderId();
}
@Override
public void delete(final Long encryptId) {
Query query = entityManager.createQuery("DELETE FROM OrderEncryptEntity e WHERE e.encryptId = ?1");
query.setParameter(1, encryptId);
query.executeUpdate();
}
@Override
public void update(final String encryptId) {
Query query = entityManager.createQuery("UPDATE OrderEncryptEntity SET e.encryptId = 11 WHERE e.encryptId = ?1");
query.setParameter(1, encryptId);
query.executeUpdate();
}
@SuppressWarnings("unchecked")
@Override
public List<OrderEncrypt> selectAll() {
return (List<OrderEncrypt>) entityManager.createQuery("SELECT e FROM OrderEntity o, OrderEncryptEntity e WHERE o.orderId = e.orderId").getResultList();
}
@SuppressWarnings("unchecked")
@Override
public List<OrderEncrypt> selectRange() {
return (List<OrderEncrypt>) entityManager.createQuery("SELECT e FROM OrderEntity o, OrderEncryptEntity e WHERE o.orderId = e.orderId AND o.userId BETWEEN 1 AND 5").getResultList();
}
}
/*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package io.shardingsphere.example.repository.mybatis.repository;
import io.shardingsphere.example.repository.api.repository.OrderEncryptRepository;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface MybatisOrderEncryptRepository extends OrderEncryptRepository {
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="io.shardingsphere.example.repository.mybatis.repository.MybatisOrderEncryptRepository">
<resultMap id="baseResultMap" type="io.shardingsphere.example.repository.api.entity.OrderEncrypt">
<result column="order_id" property="orderId" jdbcType="INTEGER"/>
<result column="user_id" property="userId" jdbcType="INTEGER"/>
<result column="encrypt_id" property="encryptId" jdbcType="VARCHAR"/>
<result column="query_id" property="queryId" jdbcType="VARCHAR"/>
</resultMap>
<update id="createTableIfNotExists">
CREATE TABLE IF NOT EXISTS t_order_encrypt (order_id BIGINT NOT NULL, user_id INT NOT NULL, encrypt_id VARCHAR(200), query_id VARCHAR(200), PRIMARY KEY (order_id));
</update>
<update id="truncateTable">
TRUNCATE TABLE t_order_encrypt;
</update>
<update id="dropTable">
DROP TABLE IF EXISTS t_order_encrypt;
</update>
<insert id="insert" useGeneratedKeys="true" keyProperty="orderId">
INSERT INTO t_order_encrypt (order_id, user_id, encrypt_id) VALUES (#{orderId,jdbcType=INTEGER}, #{userId,jdbcType=INTEGER}, #{encryptId,jdbcType=VARCHAR})
</insert>
<delete id="delete">
DELETE FROM t_order_encrypt WHERE encrypt_id = #{encryptId,jdbcType=VARCHAR};
</delete>
<update id="update">
UPDATE FROM t_order_encrypt SET encrypt_id = 11 WHERE encrypt_id = #{encryptId,jdbcType=VARCHAR};
</update>
<select id="selectAll" resultMap="baseResultMap">
SELECT e.* FROM t_order o, t_order_encrypt e WHERE o.order_id = e.order_id;
</select>
<select id="selectRange" resultMap="baseResultMap">
SELECT e.* FROM t_order o, t_order_encrypt e WHERE o.order_id = e.order_id AND o.user_id BETWEEN 1 AND 5
</select>
</mapper>
/*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package io.shardingsphere.example.repository.api.entity;
import java.io.Serializable;
public class OrderEncrypt implements Serializable {
private static final long serialVersionUID = 863434701950670170L;
private long orderId;
private int userId;
private String encryptId;
private String queryId;
public long getOrderId() {
return orderId;
}
public void setOrderId(final long orderId) {
this.orderId = orderId;
}
public int getUserId() {
return userId;
}
public void setUserId(final int userId) {
this.userId = userId;
}
public String getEncryptId() {
return encryptId;
}
public void setEncryptId(final String encryptId) {
this.encryptId = encryptId;
}
public String getQueryId() {
return queryId;
}
public void setQueryId(final String queryId) {
this.queryId = queryId;
}
@Override
public String toString() {
return String.format("order_id: %s, user_id: %s, encryptId: %s, queryId: %s", orderId, userId, encryptId, queryId);
}
}
/*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package io.shardingsphere.example.repository.api.repository;
import io.shardingsphere.example.repository.api.entity.OrderEncrypt;
public interface OrderEncryptRepository extends CommonRepository<OrderEncrypt> {
void update(String id);
}
version: '3'
services:
mysql:
## mysql version, you could get more tags at here : https://hub.docker.com/_/mysql?tab=tags
image: "mysql:5.7"
## default port is 3306, you could change to 33060 or any other port doesn't conflict MySQL on your OS
ports:
- "3306:3306"
container_name: sharding-sphere-mysql
## launch mysql without password
## you could access the mysql in container by following command :
## docker exec -it sharding-sphere-mysql mysql -uroot
environment:
- MYSQL_ALLOW_EMPTY_PASSWORD=yes
## if you insist to use password in mysql, remove MYSQL_ALLOW_EMPTY_PASSWORD=yes and uncomment following args
# - MYSQL_ROOT_PASSWORD=root
volumes:
- ../../../src/resources/manual_schema.sql:/docker-entrypoint-initdb.d/manual_schema.sql
zookeeper:
## get more versions of zookeeper here : https://hub.docker.com/_/zookeeper?tab=tags
image: "zookeeper:3.4"
ports:
- "2181:2181"
container_name: sharding-sphere-zookeeper
etcd:
## get more versions of etcd here : https://quay.io/repository/coreos/etcd?tag=latest&tab=tags
image: "quay.io/coreos/etcd:v3.3.12"
ports:
- "2379:2379"
- "2380:2380"
- "4001:4001"
container_name: sharding-sphere-etcd
entrypoint: /usr/local/bin/etcd
command:
- '--advertise-client-urls=http://0.0.0.0:2379'
- '--listen-client-urls=http://0.0.0.0:2379'
- '--initial-advertise-peer-urls=http://0.0.0.0:2380'
- '--listen-peer-urls=http://0.0.0.0:2380'
- '--initial-cluster'
- 'default=http://0.0.0.0:2380'
######################################################################################################
#
# Here you can configure the rules for the proxy.
# This example is configuration of sharding rule.
#
# If you want to use sharding, please refer to this file;
# if you want to use master-slave, please refer to the config-master_slave.yaml.
#
######################################################################################################
schemaName: sharding_db
dataSources:
ds_0:
url: jdbc:mysql://sharding-sphere-mysql:3306/demo_ds_0?serverTimezone=UTC&useSSL=false
username: root
password:
connectionTimeoutMilliseconds: 30000
idleTimeoutMilliseconds: 60000
maxLifetimeMilliseconds: 1800000
maxPoolSize: 50
ds_1:
url: jdbc:mysql://sharding-sphere-mysql:3306/demo_ds_1?serverTimezone=UTC&useSSL=false
username: root
password:
connectionTimeoutMilliseconds: 30000
idleTimeoutMilliseconds: 60000
maxLifetimeMilliseconds: 1800000
maxPoolSize: 50
shardingRule:
tables:
t_order:
actualDataNodes: ds_${0..1}.t_order_${0..1}
tableStrategy:
inline:
shardingColumn: order_id
algorithmExpression: t_order_${order_id % 2}
keyGeneratorColumnName: order_id
t_order_item:
actualDataNodes: ds_${0..1}.t_order_item_${0..1}
tableStrategy:
inline:
shardingColumn: order_id
algorithmExpression: t_order_item_${order_id % 2}
keyGeneratorColumnName: order_item_id
bindingTables:
- t_order,t_order_item
defaultDatabaseStrategy:
inline:
shardingColumn: user_id
algorithmExpression: ds_${user_id % 2}
defaultTableStrategy:
none:
defaultKeyGeneratorClassName: io.shardingsphere.core.keygen.DefaultKeyGenerator
######################################################################################################
#
# If you want to configure orchestration, authorization and proxy properties, please refer to this file.
#
######################################################################################################
#orchestration:
# name: orchestration_ds
# overwrite: true
# registry:
# serverLists: localhost:2181
# namespace: orchestration
#
authentication:
username: root
password: root
props:
max.connections.size.per.query: 1
acceptor.size: 16 # The default value is available processors count * 2.
executor.size: 16 # Infinite by default.
proxy.frontend.flush.threshold: 128 # The default value is 128.
# LOCAL: Proxy will run with LOCAL transaction.
# XA: Proxy will run with XA transaction.
# BASE: Proxy will run with B.A.S.E transaction.
proxy.transaction.type: LOCAL
proxy.opentracing.enabled: false
sql.show: false
version: '3'
services:
mysql:
## mysql version, you could get more tags at here : https://hub.docker.com/_/mysql?tab=tags
image: "mysql:5.7"
## default port is 3306, you could change to 33060 or any other port doesn't conflict MySQL on your OS
ports:
- "33060:3306"
container_name: sharding-sphere-mysql
## launch mysql without password
## you could access the mysql in container by following command :
## docker exec -it sharding-sphere-mysql mysql -uroot
environment:
- MYSQL_ALLOW_EMPTY_PASSWORD=yes
## if you insist to use password in mysql, remove MYSQL_ALLOW_EMPTY_PASSWORD=yes and uncomment following args
# - MYSQL_ROOT_PASSWORD=root
volumes:
- ../../../src/resources/manual_schema.sql:/docker-entrypoint-initdb.d/manual_schema.sql
proxy:
## get more versions of proxy here : https://hub.docker.com/r/shardingsphere/sharding-proxy/tags
image: "shardingsphere/sharding-proxy:3.1.0"
container_name: sharding-sphere-proxy
depends_on:
- mysql
## wait-for-it.sh will make proxy entrypoint wait until mysql container 3306 port open
entrypoint: >
/bin/sh -c "/opt/wait-for-it.sh sharding-sphere-mysql:3306 --timeout=20 --strict --
&& /opt/sharding-proxy/bin/start.sh 3308
&& tail -f /opt/sharding-proxy/logs/stdout.log"
ports:
- "13308:3308"
links:
- "mysql:mysql"
volumes:
- ./conf/:/opt/sharding-proxy/conf
- ../../tools/wait-for-it.sh:/opt/wait-for-it.sh
environment:
- JVM_OPTS="-Djava.awt.headless=true"
#!/usr/bin/env bash
# Use this script to test if a given TCP host/port are available
WAITFORIT_cmdname=${0##*/}
echoerr() { if [[ $WAITFORIT_QUIET -ne 1 ]]; then echo "$@" 1>&2; fi }
usage()
{
cat << USAGE >&2
Usage:
$WAITFORIT_cmdname host:port [-s] [-t timeout] [-- command args]
-h HOST | --host=HOST Host or IP under test
-p PORT | --port=PORT TCP port under test
Alternatively, you specify the host and port as host:port
-s | --strict Only execute subcommand if the test succeeds
-q | --quiet Don't output any status messages
-t TIMEOUT | --timeout=TIMEOUT
Timeout in seconds, zero for no timeout
-- COMMAND ARGS Execute command with args after the test finishes
USAGE
exit 1
}
wait_for()
{
if [[ $WAITFORIT_TIMEOUT -gt 0 ]]; then
echoerr "$WAITFORIT_cmdname: waiting $WAITFORIT_TIMEOUT seconds for $WAITFORIT_HOST:$WAITFORIT_PORT"
else
echoerr "$WAITFORIT_cmdname: waiting for $WAITFORIT_HOST:$WAITFORIT_PORT without a timeout"
fi
WAITFORIT_start_ts=$(date +%s)
while :
do
if [[ $WAITFORIT_ISBUSY -eq 1 ]]; then
nc -z $WAITFORIT_HOST $WAITFORIT_PORT
WAITFORIT_result=$?
else
(echo > /dev/tcp/$WAITFORIT_HOST/$WAITFORIT_PORT) >/dev/null 2>&1
WAITFORIT_result=$?
fi
if [[ $WAITFORIT_result -eq 0 ]]; then
WAITFORIT_end_ts=$(date +%s)
echoerr "$WAITFORIT_cmdname: $WAITFORIT_HOST:$WAITFORIT_PORT is available after $((WAITFORIT_end_ts - WAITFORIT_start_ts)) seconds"
break
fi
sleep 1
done
return $WAITFORIT_result
}
wait_for_wrapper()
{
# In order to support SIGINT during timeout: http://unix.stackexchange.com/a/57692
if [[ $WAITFORIT_QUIET -eq 1 ]]; then
timeout $WAITFORIT_BUSYTIMEFLAG $WAITFORIT_TIMEOUT $0 --quiet --child --host=$WAITFORIT_HOST --port=$WAITFORIT_PORT --timeout=$WAITFORIT_TIMEOUT &
else
timeout $WAITFORIT_BUSYTIMEFLAG $WAITFORIT_TIMEOUT $0 --child --host=$WAITFORIT_HOST --port=$WAITFORIT_PORT --timeout=$WAITFORIT_TIMEOUT &
fi
WAITFORIT_PID=$!
trap "kill -INT -$WAITFORIT_PID" INT
wait $WAITFORIT_PID
WAITFORIT_RESULT=$?
if [[ $WAITFORIT_RESULT -ne 0 ]]; then
echoerr "$WAITFORIT_cmdname: timeout occurred after waiting $WAITFORIT_TIMEOUT seconds for $WAITFORIT_HOST:$WAITFORIT_PORT"
fi
return $WAITFORIT_RESULT
}
# process arguments
while [[ $# -gt 0 ]]
do
case "$1" in
*:* )
WAITFORIT_hostport=(${1//:/ })
WAITFORIT_HOST=${WAITFORIT_hostport[0]}
WAITFORIT_PORT=${WAITFORIT_hostport[1]}
shift 1
;;
--child)
WAITFORIT_CHILD=1
shift 1
;;
-q | --quiet)
WAITFORIT_QUIET=1
shift 1
;;
-s | --strict)
WAITFORIT_STRICT=1
shift 1
;;
-h)
WAITFORIT_HOST="$2"
if [[ $WAITFORIT_HOST == "" ]]; then break; fi
shift 2
;;
--host=*)
WAITFORIT_HOST="${1#*=}"
shift 1
;;
-p)
WAITFORIT_PORT="$2"
if [[ $WAITFORIT_PORT == "" ]]; then break; fi
shift 2
;;
--port=*)
WAITFORIT_PORT="${1#*=}"
shift 1
;;
-t)
WAITFORIT_TIMEOUT="$2"
if [[ $WAITFORIT_TIMEOUT == "" ]]; then break; fi
shift 2
;;
--timeout=*)
WAITFORIT_TIMEOUT="${1#*=}"
shift 1
;;
--)
shift
WAITFORIT_CLI=("$@")
break
;;
--help)
usage
;;
*)
echoerr "Unknown argument: $1"
usage
;;
esac
done
if [[ "$WAITFORIT_HOST" == "" || "$WAITFORIT_PORT" == "" ]]; then
echoerr "Error: you need to provide a host and port to test."
usage
fi
WAITFORIT_TIMEOUT=${WAITFORIT_TIMEOUT:-15}
WAITFORIT_STRICT=${WAITFORIT_STRICT:-0}
WAITFORIT_CHILD=${WAITFORIT_CHILD:-0}
WAITFORIT_QUIET=${WAITFORIT_QUIET:-0}
# check to see if timeout is from busybox?
WAITFORIT_TIMEOUT_PATH=$(type -p timeout)
WAITFORIT_TIMEOUT_PATH=$(realpath $WAITFORIT_TIMEOUT_PATH 2>/dev/null || readlink -f $WAITFORIT_TIMEOUT_PATH)
if [[ $WAITFORIT_TIMEOUT_PATH =~ "busybox" ]]; then
WAITFORIT_ISBUSY=1
WAITFORIT_BUSYTIMEFLAG="-t"
else
WAITFORIT_ISBUSY=0
WAITFORIT_BUSYTIMEFLAG=""
fi
if [[ $WAITFORIT_CHILD -gt 0 ]]; then
wait_for
WAITFORIT_RESULT=$?
exit $WAITFORIT_RESULT
else
if [[ $WAITFORIT_TIMEOUT -gt 0 ]]; then
wait_for_wrapper
WAITFORIT_RESULT=$?
else
wait_for
WAITFORIT_RESULT=$?
fi
fi
if [[ $WAITFORIT_CLI != "" ]]; then
if [[ $WAITFORIT_RESULT -ne 0 && $WAITFORIT_STRICT -eq 1 ]]; then
echoerr "$WAITFORIT_cmdname: strict mode, refusing to execute subprocess"
exit $WAITFORIT_RESULT
fi
exec "${WAITFORIT_CLI[@]}"
else
exit $WAITFORIT_RESULT
fi
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.shardingsphere</groupId>
<artifactId>example-common</artifactId>
<version>4.0.0-RC1-SNAPSHOT</version>
</parent>
<artifactId>config-utility</artifactId>
<dependencies>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-core-api</artifactId>
</dependency>
</dependencies>
</project>
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.algorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import java.util.Collection;
public final class PreciseModuloShardingDatabaseAlgorithm implements PreciseShardingAlgorithm<Integer> {
@Override
public String doSharding(final Collection<String> databaseNames, final PreciseShardingValue<Integer> shardingValue) {
for (String each : databaseNames) {
if (each.endsWith(shardingValue.getValue() % 2 + "")) {
return each;
}
}
throw new UnsupportedOperationException();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.algorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import java.util.Collection;
public final class PreciseModuloShardingTableAlgorithm implements PreciseShardingAlgorithm<Long> {
@Override
public String doSharding(final Collection<String> tableNames, final PreciseShardingValue<Long> shardingValue) {
for (String each : tableNames) {
if (each.endsWith(shardingValue.getValue() % 2 + "")) {
return each;
}
}
throw new UnsupportedOperationException();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.algorithm;
import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
public final class RangeModuloShardingDatabaseAlgorithm implements RangeShardingAlgorithm<Integer> {
@Override
public Collection<String> doSharding(final Collection<String> databaseNames, final RangeShardingValue<Integer> shardingValueRange) {
Set<String> result = new LinkedHashSet<>();
if (Range.closed(1, 5).encloses(shardingValueRange.getValueRange())) {
for (String each : databaseNames) {
if (each.endsWith("0")) {
result.add(each);
}
}
} else if (Range.closed(6, 10).encloses(shardingValueRange.getValueRange())) {
for (String each : databaseNames) {
if (each.endsWith("1")) {
result.add(each);
}
}
} else if (Range.closed(1, 10).encloses(shardingValueRange.getValueRange())) {
result.addAll(databaseNames);
} else {
throw new UnsupportedOperationException();
}
return result;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.algorithm;
import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
public final class RangeModuloShardingTableAlgorithm implements RangeShardingAlgorithm<Long> {
@Override
public Collection<String> doSharding(final Collection<String> tableNames, final RangeShardingValue<Long> shardingValue) {
Set<String> result = new LinkedHashSet<>();
if (Range.closed(200000000000000000L, 400000000000000000L).encloses(shardingValue.getValueRange())) {
for (String each : tableNames) {
if (each.endsWith("0")) {
result.add(each);
}
}
} else {
throw new UnsupportedOperationException();
}
return result;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.config;
import javax.sql.DataSource;
import java.sql.SQLException;
public interface ExampleConfiguration {
DataSource getDataSource() throws SQLException;
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.type;
public enum RegistryCenterType {
ZOOKEEPER, ETCD
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.type;
public enum ShardingType {
SHARDING_DATABASES,
SHARDING_TABLES,
SHARDING_DATABASES_AND_TABLES,
MASTER_SLAVE,
SHARDING_MASTER_SLAVE,
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-sphere-example</artifactId>
<version>4.0.0-RC1-SNAPSHOT</version>
</parent>
<artifactId>example-common</artifactId>
<packaging>pom</packaging>
<modules>
<module>repository-api</module>
<module>repository-jpa</module>
<module>repository-mybatis</module>
<module>config-utility</module>
<module>repository-jdbc</module>
</modules>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.shardingsphere</groupId>
<artifactId>example-common</artifactId>
<version>4.0.0-RC1-SNAPSHOT</version>
</parent>
<artifactId>repository-api</artifactId>
</project>
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common;
import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;
public class DataSourceUtil {
private static final String HOST = "localhost";
private static final int PORT = 3306;
private static final String USER_NAME = "root";
private static final String PASSWORD = "";
public static DataSource createDataSource(final String dataSourceName) {
HikariDataSource result = new HikariDataSource();
result.setDriverClassName(com.mysql.jdbc.Driver.class.getName());
result.setJdbcUrl(String.format("jdbc:mysql://%s:%s/%s?serverTimezone=UTC&useSSL=false", HOST, PORT, dataSourceName));
result.setUsername(USER_NAME);
result.setPassword(PASSWORD);
return result;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.entity;
import java.io.Serializable;
public class Order implements Serializable {
private static final long serialVersionUID = 661434701950670670L;
private long orderId;
private int userId;
private String status;
public long getOrderId() {
return orderId;
}
public void setOrderId(final long orderId) {
this.orderId = orderId;
}
public int getUserId() {
return userId;
}
public void setUserId(final int userId) {
this.userId = userId;
}
public String getStatus() {
return status;
}
public void setStatus(final String status) {
this.status = status;
}
@Override
public String toString() {
return String.format("order_id: %s, user_id: %s, status: %s", orderId, userId, status);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.entity;
import java.io.Serializable;
public class OrderItem implements Serializable {
private static final long serialVersionUID = 263434701950670170L;
private long orderItemId;
private long orderId;
private int userId;
private String status;
public long getOrderItemId() {
return orderItemId;
}
public void setOrderItemId(final long orderItemId) {
this.orderItemId = orderItemId;
}
public long getOrderId() {
return orderId;
}
public void setOrderId(final long orderId) {
this.orderId = orderId;
}
public int getUserId() {
return userId;
}
public void setUserId(final int userId) {
this.userId = userId;
}
public String getStatus() {
return status;
}
public void setStatus(final String status) {
this.status = status;
}
@Override
public String toString() {
return String.format("order_item_id:%s, order_id: %s, user_id: %s, status: %s", orderItemId, orderId, userId, status);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.repository;
import java.util.List;
public interface CommonRepository<T> {
void createTableIfNotExists();
void dropTable();
void truncateTable();
Long insert(T entity);
void delete(Long id);
List<T> selectAll();
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.repository;
import io.shardingsphere.example.common.entity.OrderItem;
public interface OrderItemRepository extends CommonRepository<OrderItem> {
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.repository;
import io.shardingsphere.example.common.entity.Order;
public interface OrderRepository extends CommonRepository<Order> {
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.service;
public interface CommonService {
void initEnvironment();
void cleanEnvironment();
void processSuccess();
void processFailure();
void printData();
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.shardingsphere</groupId>
<artifactId>example-common</artifactId>
<version>4.0.0-RC1-SNAPSHOT</version>
</parent>
<artifactId>repository-jdbc</artifactId>
<dependencies>
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>config-utility</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>repository-api</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.jdbc.repository;
import io.shardingsphere.example.common.entity.OrderItem;
import io.shardingsphere.example.common.repository.OrderItemRepository;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
public class OrderItemRepositoryImpl implements OrderItemRepository {
private final DataSource dataSource;
public OrderItemRepositoryImpl(final DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void createTableIfNotExists() {
String sql = "CREATE TABLE IF NOT EXISTS t_order_item "
+ "(order_item_id BIGINT NOT NULL AUTO_INCREMENT, order_id BIGINT NOT NULL, user_id INT NOT NULL, status VARCHAR(50), PRIMARY KEY (order_item_id))";
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.executeUpdate(sql);
} catch (final SQLException ignored) {
}
}
@Override
public void dropTable() {
String sql = "DROP TABLE t_order_item";
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.executeUpdate(sql);
} catch (final SQLException ignored) {
}
}
@Override
public void truncateTable() {
String sql = "TRUNCATE TABLE t_order_item";
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.executeUpdate(sql);
} catch (final SQLException ignored) {
}
}
@Override
public Long insert(final OrderItem orderItem) {
String sql = "INSERT INTO t_order_item (order_id, user_id, status) VALUES (?, ?, ?)";
try (Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
preparedStatement.setLong(1, orderItem.getOrderId());
preparedStatement.setInt(2, orderItem.getUserId());
preparedStatement.setString(3, orderItem.getStatus());
preparedStatement.executeUpdate();
try (ResultSet resultSet = preparedStatement.getGeneratedKeys()) {
if (resultSet.next()) {
orderItem.setOrderItemId(resultSet.getLong(1));
}
}
} catch (final SQLException ignored) {
}
return orderItem.getOrderItemId();
}
@Override
public void delete(final Long orderItemId) {
String sql = "DELETE FROM t_order_item WHERE order_item_id=?";
try (Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setLong(1, orderItemId);
preparedStatement.executeUpdate();
} catch (final SQLException ignored) {
}
}
@Override
public List<OrderItem> selectAll() {
String sql = "SELECT i.* FROM t_order o, t_order_item i WHERE o.order_id = i.order_id";
return getOrderItems(sql);
}
protected List<OrderItem> getOrderItems(final String sql) {
List<OrderItem> result = new LinkedList<>();
try (Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
OrderItem orderItem = new OrderItem();
orderItem.setOrderItemId(resultSet.getLong(1));
orderItem.setOrderId(resultSet.getLong(2));
orderItem.setUserId(resultSet.getInt(3));
orderItem.setStatus(resultSet.getString(4));
result.add(orderItem);
}
} catch (final SQLException ignored) {
}
return result;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.jdbc.repository;
import io.shardingsphere.example.common.entity.Order;
import io.shardingsphere.example.common.repository.OrderRepository;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
public class OrderRepositoryImpl implements OrderRepository {
private final DataSource dataSource;
public OrderRepositoryImpl(final DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void createTableIfNotExists() {
String sql = "CREATE TABLE IF NOT EXISTS t_order (order_id BIGINT NOT NULL AUTO_INCREMENT, user_id INT NOT NULL, status VARCHAR(50), PRIMARY KEY (order_id))";
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.executeUpdate(sql);
} catch (final SQLException ignored) {
}
}
@Override
public void dropTable() {
String sql = "DROP TABLE t_order";
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.executeUpdate(sql);
} catch (final SQLException ignored) {
}
}
@Override
public void truncateTable() {
String sql = "TRUNCATE TABLE t_order";
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.executeUpdate(sql);
} catch (final SQLException ignored) {
}
}
@Override
public Long insert(final Order order) {
String sql = "INSERT INTO t_order (user_id, status) VALUES (?, ?)";
try (Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
preparedStatement.setInt(1, order.getUserId());
preparedStatement.setString(2, order.getStatus());
preparedStatement.executeUpdate();
try (ResultSet resultSet = preparedStatement.getGeneratedKeys()) {
if (resultSet.next()) {
order.setOrderId(resultSet.getLong(1));
}
}
} catch (final SQLException ignored) {
}
return order.getOrderId();
}
@Override
public void delete(final Long orderId) {
String sql = "DELETE FROM t_order WHERE order_id=?";
try (Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setLong(1, orderId);
preparedStatement.executeUpdate();
} catch (final SQLException ignored) {
}
}
@Override
public List<Order> selectAll() {
String sql = "SELECT * FROM t_order";
return getOrders(sql);
}
protected List<Order> getOrders(final String sql) {
List<Order> result = new LinkedList<>();
try (Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
Order order = new Order();
order.setOrderId(resultSet.getLong(1));
order.setUserId(resultSet.getInt(2));
order.setStatus(resultSet.getString(3));
result.add(order);
}
} catch (final SQLException ignored) {
}
return result;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.jdbc.repository;
import io.shardingsphere.example.common.entity.OrderItem;
import javax.sql.DataSource;
import java.util.List;
public final class RangeOrderItemRepositoryImpl extends OrderItemRepositoryImpl {
public RangeOrderItemRepositoryImpl(final DataSource dataSource) {
super(dataSource);
}
@Override
public List<OrderItem> selectAll() {
String sql = "SELECT i.* FROM t_order o, t_order_item i WHERE o.order_id = i.order_id AND o.user_id BETWEEN 1 AND 5";
return getOrderItems(sql);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.jdbc.repository;
import io.shardingsphere.example.common.entity.Order;
import javax.sql.DataSource;
import java.util.List;
public final class RangeOrderRepositoryImpl extends OrderRepositoryImpl {
public RangeOrderRepositoryImpl(final DataSource dataSource) {
super(dataSource);
}
@Override
public List<Order> selectAll() {
String sql = "SELECT * FROM t_order WHERE order_id BETWEEN 200000000000000000 AND 400000000000000000";
return getOrders(sql);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.jdbc.service;
import io.shardingsphere.example.common.entity.Order;
import io.shardingsphere.example.common.entity.OrderItem;
import io.shardingsphere.example.common.repository.OrderItemRepository;
import io.shardingsphere.example.common.repository.OrderRepository;
import io.shardingsphere.example.common.service.CommonService;
import java.util.ArrayList;
import java.util.List;
public final class CommonServiceImpl implements CommonService {
private OrderRepository orderRepository;
private OrderItemRepository orderItemRepository;
public CommonServiceImpl(final OrderRepository orderRepository, final OrderItemRepository orderItemRepository) {
this.orderRepository = orderRepository;
this.orderItemRepository = orderItemRepository;
}
@Override
public void initEnvironment() {
orderRepository.createTableIfNotExists();
orderItemRepository.createTableIfNotExists();
orderRepository.truncateTable();
orderItemRepository.truncateTable();
}
@Override
public void cleanEnvironment() {
orderRepository.dropTable();
orderItemRepository.dropTable();
}
@Override
public void processSuccess() {
System.out.println("-------------- Process Success Begin ---------------");
List<Long> orderIds = insertData();
printData();
deleteData(orderIds);
printData();
System.out.println("-------------- Process Success Finish --------------");
}
@Override
public void processFailure() {
System.out.println("-------------- Process Failure Begin ---------------");
insertData();
System.out.println("-------------- Process Failure Finish --------------");
throw new RuntimeException("Exception occur for transaction test.");
}
private List<Long> insertData() {
System.out.println("---------------------------- Insert Data ----------------------------");
List<Long> result = new ArrayList<>(10);
for (int i = 1; i <= 10; i++) {
Order order = new Order();
order.setUserId(i);
order.setStatus("INSERT_TEST");
orderRepository.insert(order);
OrderItem item = new OrderItem();
item.setOrderId(order.getOrderId());
item.setUserId(i);
item.setStatus("INSERT_TEST");
orderItemRepository.insert(item);
result.add(order.getOrderId());
}
return result;
}
private void deleteData(final List<Long> orderIds) {
System.out.println("---------------------------- Delete Data ----------------------------");
for (Long each : orderIds) {
orderRepository.delete(each);
orderItemRepository.delete(each);
}
}
@Override
public void printData() {
System.out.println("---------------------------- Print Order Data -----------------------");
for (Object each : orderRepository.selectAll()) {
System.out.println(each);
}
System.out.println("---------------------------- Print OrderItem Data -------------------");
for (Object each : orderItemRepository.selectAll()) {
System.out.println(each);
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.shardingsphere</groupId>
<artifactId>example-common</artifactId>
<version>4.0.0-RC1-SNAPSHOT</version>
</parent>
<artifactId>repository-jpa</artifactId>
<dependencies>
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>repository-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
</dependencies>
</project>
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.jpa.entity;
import io.shardingsphere.example.common.entity.Order;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "t_order")
public final class OrderEntity extends Order {
@Id
@Column(name = "order_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Override
public long getOrderId() {
return super.getOrderId();
}
@Column(name = "user_id")
@Override
public int getUserId() {
return super.getUserId();
}
@Column(name = "status")
public String getStatus() {
return super.getStatus();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.jpa.entity;
import io.shardingsphere.example.common.entity.OrderItem;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "t_order_item")
public final class OrderItemEntity extends OrderItem {
@Id
@Column(name = "order_item_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Override
public long getOrderItemId() {
return super.getOrderItemId();
}
@Column(name = "order_id")
@Override
public long getOrderId() {
return super.getOrderId();
}
@Column(name = "user_id")
@Override
public int getUserId() {
return super.getUserId();
}
@Column(name = "status")
@Override
public String getStatus() {
return super.getStatus();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.jpa.repository;
import io.shardingsphere.example.common.entity.OrderItem;
import io.shardingsphere.example.common.repository.OrderItemRepository;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.util.List;
@Repository
@Transactional
public class OrderItemRepositoryImpl implements OrderItemRepository {
@PersistenceContext
private EntityManager entityManager;
@Override
public void createTableIfNotExists() {
throw new UnsupportedOperationException("createTableIfNotExists for JPA");
}
@Override
public void truncateTable() {
throw new UnsupportedOperationException("truncateTable for JPA");
}
@Override
public void dropTable() {
throw new UnsupportedOperationException("dropTable for JPA");
}
@Override
public Long insert(final OrderItem orderItem) {
entityManager.persist(orderItem);
return orderItem.getOrderItemId();
}
@Override
public void delete(final Long orderItemId) {
Query query = entityManager.createQuery("DELETE FROM OrderItemEntity i WHERE i.orderItemId = ?1 AND i.userId = 51");
query.setParameter(1, orderItemId);
query.executeUpdate();
}
@SuppressWarnings("unchecked")
@Override
public List<OrderItem> selectAll() {
return (List<OrderItem>) entityManager.createQuery("SELECT i FROM OrderEntity o, OrderItemEntity i WHERE o.orderId = i.orderId").getResultList();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.jpa.repository;
import io.shardingsphere.example.common.entity.Order;
import io.shardingsphere.example.common.repository.OrderRepository;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.util.List;
@Repository
@Transactional
public class OrderRepositoryImpl implements OrderRepository {
@PersistenceContext
private EntityManager entityManager;
@Override
public void createTableIfNotExists() {
throw new UnsupportedOperationException("createTableIfNotExists for JPA");
}
@Override
public void truncateTable() {
throw new UnsupportedOperationException("truncateTable for JPA");
}
@Override
public void dropTable() {
throw new UnsupportedOperationException("dropTable for JPA");
}
@Override
public Long insert(final Order order) {
entityManager.persist(order);
return order.getOrderId();
}
@Override
public void delete(final Long orderId) {
Query query = entityManager.createQuery("DELETE FROM OrderEntity o WHERE o.orderId = ?1");
query.setParameter(1, orderId);
query.executeUpdate();
}
@SuppressWarnings("unchecked")
@Override
public List<Order> selectAll() {
return (List<Order>) entityManager.createQuery("SELECT o FROM OrderEntity o").getResultList();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.jpa.service;
import io.shardingsphere.example.common.service.CommonService;
public interface JPACommonService extends CommonService {
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.jpa.service;
import io.shardingsphere.example.common.jpa.entity.OrderEntity;
import io.shardingsphere.example.common.jpa.entity.OrderItemEntity;
import io.shardingsphere.example.common.repository.OrderItemRepository;
import io.shardingsphere.example.common.repository.OrderRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Service
public class JPACommonServiceImpl implements JPACommonService {
@Resource
private OrderRepository orderRepository;
@Resource
private OrderItemRepository orderItemRepository;
@Override
public void initEnvironment() {
}
@Override
public void cleanEnvironment() {
}
@Override
@Transactional
public void processSuccess() {
System.out.println("-------------- Process Success Begin ---------------");
List<Long> orderIds = insertData();
printData();
deleteData(orderIds);
printData();
System.out.println("-------------- Process Success Finish --------------");
}
@Override
@Transactional
public void processFailure() {
System.out.println("-------------- Process Failure Begin ---------------");
insertData();
System.out.println("-------------- Process Failure Finish --------------");
throw new RuntimeException("Exception occur for transaction test.");
}
private List<Long> insertData() {
System.out.println("---------------------------- Insert Data ----------------------------");
List<Long> result = new ArrayList<>(10);
for (int i = 1; i <= 10; i++) {
OrderEntity order = new OrderEntity();
order.setUserId(i);
order.setStatus("INSERT_TEST_JPA");
orderRepository.insert(order);
OrderItemEntity item = new OrderItemEntity();
item.setOrderId(order.getOrderId());
item.setUserId(i);
item.setStatus("INSERT_TEST_JPA");
orderItemRepository.insert(item);
result.add(order.getOrderId());
}
return result;
}
private void deleteData(final List<Long> orderIds) {
System.out.println("---------------------------- Delete Data ----------------------------");
for (Long each : orderIds) {
orderRepository.delete(each);
orderItemRepository.delete(each);
}
}
@Override
public void printData() {
System.out.println("---------------------------- Print Order Data -----------------------");
for (Object each : orderRepository.selectAll()) {
System.out.println(each);
}
System.out.println("---------------------------- Print OrderItem Data -------------------");
for (Object each : orderItemRepository.selectAll()) {
System.out.println(each);
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.shardingsphere</groupId>
<artifactId>example-common</artifactId>
<version>4.0.0-RC1-SNAPSHOT</version>
</parent>
<artifactId>repository-mybatis</artifactId>
<dependencies>
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>repository-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
</dependencies>
</project>
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.mybatis.repository;
import io.shardingsphere.example.common.repository.OrderItemRepository;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface MybatisOrderItemRepository extends OrderItemRepository {
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.mybatis.repository;
import io.shardingsphere.example.common.repository.OrderRepository;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface MybatisOrderRepository extends OrderRepository {
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.mybatis.service;
import io.shardingsphere.example.common.service.CommonService;
public interface SpringPojoService extends CommonService {
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.common.mybatis.service;
import io.shardingsphere.example.common.entity.Order;
import io.shardingsphere.example.common.entity.OrderItem;
import io.shardingsphere.example.common.repository.OrderItemRepository;
import io.shardingsphere.example.common.repository.OrderRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Service
public class SpringPojoServiceImpl implements SpringPojoService {
@Resource
private OrderRepository orderRepository;
@Resource
private OrderItemRepository orderItemRepository;
@Override
public void initEnvironment() {
orderRepository.createTableIfNotExists();
orderItemRepository.createTableIfNotExists();
orderRepository.truncateTable();
orderItemRepository.truncateTable();
}
@Override
public void cleanEnvironment() {
orderRepository.dropTable();
orderItemRepository.dropTable();
}
@Override
@Transactional
public void processSuccess() {
System.out.println("-------------- Process Success Begin ---------------");
List<Long> orderIds = insertData();
printData();
deleteData(orderIds);
printData();
System.out.println("-------------- Process Success Finish --------------");
}
@Override
@Transactional
public void processFailure() {
System.out.println("-------------- Process Failure Begin ---------------");
insertData();
System.out.println("-------------- Process Failure Finish --------------");
throw new RuntimeException("Exception occur for transaction test.");
}
private List<Long> insertData() {
System.out.println("---------------------------- Insert Data ----------------------------");
List<Long> result = new ArrayList<>(10);
for (int i = 1; i <= 10; i++) {
Order order = new Order();
order.setUserId(i);
order.setStatus("INSERT_TEST");
orderRepository.insert(order);
OrderItem item = new OrderItem();
item.setOrderId(order.getOrderId());
item.setUserId(i);
item.setStatus("INSERT_TEST");
orderItemRepository.insert(item);
result.add(order.getOrderId());
}
return result;
}
private void deleteData(final List<Long> orderIds) {
System.out.println("---------------------------- Delete Data ----------------------------");
for (Long each : orderIds) {
orderRepository.delete(each);
orderItemRepository.delete(each);
}
}
@Override
public void printData() {
System.out.println("---------------------------- Print Order Data -----------------------");
for (Object each : orderRepository.selectAll()) {
System.out.println(each);
}
System.out.println("---------------------------- Print OrderItem Data -------------------");
for (Object each : orderItemRepository.selectAll()) {
System.out.println(each);
}
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="io.shardingsphere.example.common.mybatis.repository.MybatisOrderItemRepository">
<resultMap id="baseResultMap" type="io.shardingsphere.example.common.entity.OrderItem">
<result column="order_item_id" property="orderItemId" jdbcType="INTEGER"/>
<result column="order_id" property="orderId" jdbcType="INTEGER"/>
<result column="user_id" property="userId" jdbcType="INTEGER"/>
<result column="status" property="status" jdbcType="VARCHAR"/>
</resultMap>
<update id="createTableIfNotExists">
CREATE TABLE IF NOT EXISTS t_order_item (order_item_id BIGINT AUTO_INCREMENT, order_id BIGINT, user_id INT NOT NULL, status VARCHAR(50) , PRIMARY KEY (order_item_id));
</update>
<update id="truncateTable">
TRUNCATE TABLE t_order_item;
</update>
<update id="dropTable">
DROP TABLE IF EXISTS t_order_item;
</update>
<insert id="insert" useGeneratedKeys="true" keyProperty="orderItemId">
INSERT INTO t_order_item (order_id, user_id, status) VALUES (#{orderId,jdbcType=INTEGER}, #{userId,jdbcType=INTEGER}, #{status,jdbcType=VARCHAR});
</insert>
<delete id="delete">
DELETE FROM t_order_item WHERE order_id = #{orderId,jdbcType=INTEGER};
</delete>
<select id="selectAll" resultMap="baseResultMap">
SELECT i.* FROM t_order o, t_order_item i WHERE o.order_id = i.order_id;
</select>
<select id="selectRange" resultMap="baseResultMap">
SELECT i.* FROM t_order o, t_order_item i WHERE o.order_id = i.order_id AND o.user_id BETWEEN 1 AND 5
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="io.shardingsphere.example.common.mybatis.repository.MybatisOrderRepository">
<resultMap id="baseResultMap" type="io.shardingsphere.example.common.entity.Order">
<result column="order_id" property="orderId" jdbcType="INTEGER"/>
<result column="user_id" property="userId" jdbcType="INTEGER"/>
<result column="status" property="status" jdbcType="VARCHAR"/>
</resultMap>
<update id="createTableIfNotExists">
CREATE TABLE IF NOT EXISTS t_order (order_id BIGINT AUTO_INCREMENT, user_id INT NOT NULL, status VARCHAR(50), PRIMARY KEY (order_id));
</update>
<update id="truncateTable">
TRUNCATE TABLE t_order;
</update>
<update id="dropTable">
DROP TABLE IF EXISTS t_order;
</update>
<insert id="insert" useGeneratedKeys="true" keyProperty="orderId">
INSERT INTO t_order (user_id, status) VALUES (#{userId,jdbcType=INTEGER}, #{status,jdbcType=VARCHAR});
</insert>
<delete id="delete">
DELETE FROM t_order WHERE order_id = #{orderId,jdbcType=INTEGER};
</delete>
<select id="selectAll" resultMap="baseResultMap">
SELECT * FROM t_order;
</select>
<select id="selectRange" resultMap="baseResultMap">
SELECT * FROM t_order WHERE order_id BETWEEN 200000000000000000 AND 400000000000000000
</select>
</mapper>
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.algorithm;
import org.apache.shardingsphere.spi.algorithm.encrypt.ShardingQueryAssistedEncryptor;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Query assisted encryptor.
*
* @author panjuan
*/
public final class QueryAssistedEncryptor implements ShardingQueryAssistedEncryptor {
private final AtomicInteger count = new AtomicInteger();
private Properties properties;
@Override
public String queryAssistedEncrypt(final String plaintext) {
return "query_encrypt";
}
@Override
public String encrypt(final Object plaintext) {
return String.format("encrypt_%s", count.incrementAndGet());
}
@Override
public Object decrypt(final String ciphertext) {
return "decrypt";
}
@Override
public String getType() {
return "query";
}
@Override
public Properties getProperties() {
return properties;
}
@Override
public void setProperties(final Properties properties) {
this.properties = properties;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-sphere-example</artifactId>
<version>4.0.0-RC1-SNAPSHOT</version>
<modules>
<module>example-common</module>
<module>sharding-jdbc-example</module>
<module>sharding-proxy-example</module>
</modules>
<packaging>pom</packaging>
<properties>
<java.version>1.7</java.version>
<maven.version.range>[3.0.4,)</maven.version.range>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.build.locale>zh_CN</project.build.locale>
<sharding-sphere.version>4.0.0-RC1-SNAPSHOT</sharding-sphere.version>
<sharding-sphere.spi.impl.version>4.0.0-RC1-SNAPSHOT</sharding-sphere.spi.impl.version>
<aspectjweaver.version>1.8.9</aspectjweaver.version>
<spring-framework.version>4.3.20.RELEASE</spring-framework.version>
<spring-boot.version>1.5.17.RELEASE</spring-boot.version>
<hikari-cp.version>2.4.11</hikari-cp.version>
<mysql-connector-java.version>5.1.42</mysql-connector-java.version>
<postgresql.version>9.1-901-1.jdbc4</postgresql.version>
<slf4j.version>1.7.7</slf4j.version>
<logback.version>1.2.0</logback.version>
<mybatis.version>3.4.2</mybatis.version>
<mybatis-spring.version>1.3.0</mybatis-spring.version>
<jpa.version>1.0.0.Final</jpa.version>
<hibernate.version>4.3.11.Final</hibernate.version>
<junit.version>4.12</junit.version>
<hamcrest.version>1.3</hamcrest.version>
<mockito.version>2.7.21</mockito.version>
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<maven-jar-plugin.version>2.6</maven-jar-plugin.version>
<maven-source-plugin.version>2.4</maven-source-plugin.version>
<javadocExecutable>${java.home}/../bin/javadoc</javadocExecutable>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-core-api</artifactId>
<version>${sharding-sphere.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-core</artifactId>
<version>${sharding-sphere.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-orchestration</artifactId>
<version>${sharding-sphere.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-transaction-core</artifactId>
<version>${sharding-sphere.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-transaction-xa-core</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-transaction-base-saga</artifactId>
<version>${sharding-sphere.spi.impl.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>${sharding-sphere.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-orchestration-spring-boot-starter</artifactId>
<version>${sharding-sphere.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-namespace</artifactId>
<version>${sharding-sphere.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-orchestration-spring-namespace</artifactId>
<version>${sharding-sphere.version}</version>
</dependency>
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-transaction-spring</artifactId>
<version>${sharding-sphere.spi.impl.version}</version>
</dependency>
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-transaction-spring-boot-starter</artifactId>
<version>${sharding-sphere.spi.impl.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-orchestration-reg-zookeeper-curator</artifactId>
<version>${sharding-sphere.version}</version>
</dependency>
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-orchestration-reg-etcd</artifactId>
<version>${sharding-sphere.spi.impl.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectjweaver.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>${jpa.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP-java7</artifactId>
<version>${hikari-cp.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${hamcrest.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>${mockito.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<testSource>${java.version}</testSource>
<testTarget>${java.version}</testTarget>
</configuration>
<version>${maven-compiler-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>${maven-resources-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>${maven-source-plugin.version}</version>
<executions>
<execution>
<id>attach-sources</id>
<phase>verify</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one or more
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~ The ASF licenses this file to You under the Apache License, Version 2.0
~ (the "License"); you may not use this file except in compliance with
~ the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.shardingsphere</groupId>
<artifactId>hint-example</artifactId>
<version>4.0.0-RC1-SNAPSHOT</version>
</parent>
<artifactId>hint-raw-jdbc-example</artifactId>
<dependencies>
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>repository-jdbc</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-core</artifactId>
</dependency>
</dependencies>
</project>
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.hint.raw.jdbc;
public enum HintType {
DATABASE_ONLY, DATABASE_TABLES, MASTER_ONLY
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.hint.raw.jdbc;
import org.apache.shardingsphere.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.hint.HintShardingValue;
import java.util.Collection;
import java.util.Collections;
public final class ModuloHintShardingAlgorithm implements HintShardingAlgorithm<Long> {
@Override
public Collection<String> doSharding(final Collection<String> availableTargetNames, final HintShardingValue<Long> shardingValue) {
for (String each : availableTargetNames) {
if (each.endsWith(String.valueOf(shardingValue.getValues().iterator().next() % 2))) {
return Collections.singletonList(each);
}
}
throw new UnsupportedOperationException();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.hint.raw.jdbc;
import io.shardingsphere.example.common.jdbc.repository.OrderItemRepositoryImpl;
import io.shardingsphere.example.common.jdbc.repository.OrderRepositoryImpl;
import io.shardingsphere.example.common.jdbc.service.CommonServiceImpl;
import io.shardingsphere.example.common.service.CommonService;
import org.apache.shardingsphere.api.hint.HintManager;
import org.apache.shardingsphere.shardingjdbc.api.yaml.YamlMasterSlaveDataSourceFactory;
import org.apache.shardingsphere.shardingjdbc.api.yaml.YamlShardingDataSourceFactory;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class YamlConfigurationExample {
private static final HintType TYPE = HintType.DATABASE_TABLES;
// private static final HintType TYPE = HintType.DATABASE_ONLY;
// private static final HintType TYPE = HintType.MASTER_ONLY;
public static void main(final String[] args) throws SQLException, IOException {
DataSource dataSource = getDataSource();
CommonService commonService = getCommonService(dataSource);
commonService.initEnvironment();
processWithHintValue(dataSource);
commonService.cleanEnvironment();
}
private static DataSource getDataSource() throws IOException, SQLException {
switch (TYPE) {
case DATABASE_TABLES:
return YamlShardingDataSourceFactory.createDataSource(getFile("/META-INF/hint-databases-tables.yaml"));
case DATABASE_ONLY:
return YamlShardingDataSourceFactory.createDataSource(getFile("/META-INF/hint-databases-only.yaml"));
case MASTER_ONLY:
return YamlMasterSlaveDataSourceFactory.createDataSource(getFile("/META-INF/hint-master-only.yaml"));
default:
throw new UnsupportedOperationException("unsupported type");
}
}
private static File getFile(final String configFile) {
return new File(Thread.currentThread().getClass().getResource(configFile).getFile());
}
private static CommonService getCommonService(final DataSource dataSource) {
return new CommonServiceImpl(new OrderRepositoryImpl(dataSource), new OrderItemRepositoryImpl(dataSource));
}
private static void processWithHintValue(final DataSource dataSource) throws SQLException {
try (HintManager hintManager = HintManager.getInstance();
Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
setHintValue(hintManager);
statement.execute("select * from t_order");
statement.execute("SELECT i.* FROM t_order o, t_order_item i WHERE o.order_id = i.order_id");
statement.execute("select * from t_order_item");
statement.execute("INSERT INTO t_order (user_id, status) VALUES (1, 'init')");
}
}
private static void setHintValue(final HintManager hintManager) {
switch (TYPE) {
case DATABASE_TABLES:
hintManager.addDatabaseShardingValue("t_order", 1L);
hintManager.addTableShardingValue("t_order", 1L);
return;
case DATABASE_ONLY:
hintManager.setDatabaseShardingValue(1L);
return;
case MASTER_ONLY:
hintManager.setMasterRouteOnly();
return;
default:
throw new UnsupportedOperationException("unsupported type");
}
}
}
dataSources:
ds_0: !!com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.jdbc.Driver
jdbcUrl: jdbc:mysql://localhost:3306/demo_ds_0
username: root
password:
ds_1: !!com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.jdbc.Driver
jdbcUrl: jdbc:mysql://localhost:3306/demo_ds_1
username: root
password:
shardingRule:
tables:
t_order:
actualDataNodes: ds_${0..1}.t_order
t_order_item:
actualDataNodes: ds_${0..1}.t_order_item
bindingTables:
- t_order,t_order_item
defaultDatabaseStrategy:
hint:
algorithmClassName: io.shardingsphere.example.hint.raw.jdbc.ModuloHintShardingAlgorithm
defaultTableStrategy:
none:
props:
sql.show: true
dataSources:
ds_0: !!com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.jdbc.Driver
jdbcUrl: jdbc:mysql://localhost:3306/demo_ds_0
username: root
password:
ds_1: !!com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.jdbc.Driver
jdbcUrl: jdbc:mysql://localhost:3306/demo_ds_1
username: root
password:
shardingRule:
tables:
t_order:
actualDataNodes: ds_${0..1}.t_order_${0..1}
databaseStrategy:
hint:
algorithmClassName: io.shardingsphere.example.hint.raw.jdbc.ModuloHintShardingAlgorithm
tableStrategy:
hint:
algorithmClassName: io.shardingsphere.example.hint.raw.jdbc.ModuloHintShardingAlgorithm
keyGenerator:
type: SNOWFLAKE
column: order_id
t_order_item:
actualDataNodes: ds_${0..1}.t_order_item_${0..1}
bindingTables:
- t_order,t_order_item
defaultDatabaseStrategy:
inline:
shardingColumn: user_id
algorithmExpression: ds_${user_id % 2}
defaultTableStrategy:
none:
props:
sql.show: true
dataSources:
ds_master: !!com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.jdbc.Driver
jdbcUrl: jdbc:mysql://localhost:3306/demo_ds_master
username: root
password:
ds_slave_0: !!com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.jdbc.Driver
jdbcUrl: jdbc:mysql://localhost:3306/demo_ds_slave_0
username: root
password:
ds_slave_1: !!com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.jdbc.Driver
jdbcUrl: jdbc:mysql://localhost:3306/demo_ds_slave_1
username: root
password:
masterSlaveRule:
name: ds_ms
masterDataSourceName: ds_master
slaveDataSourceNames: [ds_slave_0, ds_slave_1]
props:
sql.show: true
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one or more
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~ The ASF licenses this file to You under the Apache License, Version 2.0
~ (the "License"); you may not use this file except in compliance with
~ the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<configuration>
<property name="log.context.name" value="hint-raw-jdbc-example" />
<property name="log.charset" value="UTF-8" />
<property name="log.pattern" value="[%-5level] %date --%thread-- [%logger] %msg %n" />
<contextName>${log.context.name}</contextName>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder charset="${log.charset}">
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="STDOUT" />
</root>
</configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one or more
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~ The ASF licenses this file to You under the Apache License, Version 2.0
~ (the "License"); you may not use this file except in compliance with
~ the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<modules>
<module>hint-raw-jdbc-example</module>
</modules>
<parent>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-jdbc-example</artifactId>
<version>4.0.0-RC1-SNAPSHOT</version>
</parent>
<artifactId>hint-example</artifactId>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.shardingsphere</groupId>
<artifactId>orchestration-example</artifactId>
<version>4.0.0-RC1-SNAPSHOT</version>
</parent>
<artifactId>orchestration-raw-jdbc-example</artifactId>
<dependencies>
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>repository-jdbc</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>config-utility</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-orchestration</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-orchestration-reg-zookeeper-curator</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>io.shardingsphere</groupId>-->
<!--<artifactId>sharding-orchestration-reg-etcd</artifactId>-->
<!--</dependency>-->
</dependencies>
</project>
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.orchestration.raw.jdbc;
import io.shardingsphere.example.common.jdbc.repository.OrderItemRepositoryImpl;
import io.shardingsphere.example.common.jdbc.repository.OrderRepositoryImpl;
import io.shardingsphere.example.common.jdbc.service.CommonServiceImpl;
import io.shardingsphere.example.common.service.CommonService;
import io.shardingsphere.example.config.ExampleConfiguration;
import io.shardingsphere.example.orchestration.raw.jdbc.config.RegistryCenterConfigurationUtil;
import io.shardingsphere.example.orchestration.raw.jdbc.config.cloud.CloudMasterSlaveConfiguration;
import io.shardingsphere.example.orchestration.raw.jdbc.config.cloud.CloudShardingDatabasesAndTablesConfiguration;
import io.shardingsphere.example.orchestration.raw.jdbc.config.local.LocalMasterSlaveConfiguration;
import io.shardingsphere.example.orchestration.raw.jdbc.config.local.LocalShardingDatabasesAndTablesConfiguration;
import io.shardingsphere.example.type.RegistryCenterType;
import io.shardingsphere.example.type.ShardingType;
import org.apache.shardingsphere.orchestration.reg.api.RegistryCenterConfiguration;
import org.apache.shardingsphere.shardingjdbc.jdbc.adapter.AbstractDataSourceAdapter;
import javax.sql.DataSource;
import java.sql.SQLException;
/*
* 1. Please make sure master-slave data sync on MySQL is running correctly. Otherwise this example will query empty data from slave.
* 2. Please make sure sharding-orchestration-reg-zookeeper-curator in your pom if registryCenterType = RegistryCenterType.ZOOKEEPER.
* 3. Please make sure sharding-orchestration-reg-etcd in your pom if registryCenterType = RegistryCenterType.ETCD.
*/
public class JavaConfigurationExample {
private static ShardingType shardingType = ShardingType.SHARDING_DATABASES_AND_TABLES;
// private static ShardingType shardingType = ShardingType.MASTER_SLAVE;
private static boolean loadConfigFromRegCenter = false;
// private static boolean loadConfigFromRegCenter = true;
private static RegistryCenterType registryCenterType = RegistryCenterType.ZOOKEEPER;
// private static RegistryCenterType registryCenterType = RegistryCenterType.ETCD;
public static void main(final String[] args) throws Exception {
DataSource dataSource = getDataSource(shardingType, loadConfigFromRegCenter);
CommonService commonService = getCommonService(dataSource);
commonService.initEnvironment();
commonService.processSuccess();
commonService.cleanEnvironment();
closeDataSource(dataSource);
}
private static DataSource getDataSource(final ShardingType shardingType, final boolean loadConfigFromRegCenter) throws SQLException {
RegistryCenterConfiguration registryCenterConfig = getRegistryCenterConfiguration(registryCenterType);
ExampleConfiguration configuration;
switch (shardingType) {
case SHARDING_DATABASES_AND_TABLES:
configuration = loadConfigFromRegCenter ? new CloudShardingDatabasesAndTablesConfiguration(registryCenterConfig) : new LocalShardingDatabasesAndTablesConfiguration(registryCenterConfig);
break;
case MASTER_SLAVE:
configuration = loadConfigFromRegCenter ? new CloudMasterSlaveConfiguration(registryCenterConfig) : new LocalMasterSlaveConfiguration(registryCenterConfig);
break;
default:
throw new UnsupportedOperationException(shardingType.name());
}
return configuration.getDataSource();
}
private static RegistryCenterConfiguration getRegistryCenterConfiguration(final RegistryCenterType registryCenterType) {
return RegistryCenterType.ZOOKEEPER == registryCenterType ? RegistryCenterConfigurationUtil.getZooKeeperConfiguration() : RegistryCenterConfigurationUtil.getEtcdConfiguration();
}
private static CommonService getCommonService(final DataSource dataSource) {
return new CommonServiceImpl(new OrderRepositoryImpl(dataSource), new OrderItemRepositoryImpl(dataSource));
}
private static void closeDataSource(final DataSource dataSource) throws Exception {
if (dataSource instanceof AbstractDataSourceAdapter) {
((AbstractDataSourceAdapter) dataSource).close();
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.orchestration.raw.jdbc;
import io.shardingsphere.example.common.jdbc.repository.OrderItemRepositoryImpl;
import io.shardingsphere.example.common.jdbc.repository.OrderRepositoryImpl;
import io.shardingsphere.example.common.jdbc.service.CommonServiceImpl;
import io.shardingsphere.example.common.service.CommonService;
import io.shardingsphere.example.type.RegistryCenterType;
import io.shardingsphere.example.type.ShardingType;
import org.apache.shardingsphere.shardingjdbc.jdbc.adapter.AbstractDataSourceAdapter;
import org.apache.shardingsphere.shardingjdbc.orchestration.api.yaml.YamlOrchestrationMasterSlaveDataSourceFactory;
import org.apache.shardingsphere.shardingjdbc.orchestration.api.yaml.YamlOrchestrationShardingDataSourceFactory;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
/*
* 1. Please make sure master-slave data sync on MySQL is running correctly. Otherwise this example will query empty data from slave.
* 2. Please make sure sharding-orchestration-reg-zookeeper-curator in your pom if registryCenterType = RegistryCenterType.ZOOKEEPER.
* 3. Please make sure sharding-orchestration-reg-etcd in your pom if registryCenterType = RegistryCenterType.ETCD.
*/
public class YamlConfigurationExample {
private static ShardingType shardingType = ShardingType.SHARDING_DATABASES_AND_TABLES;
// private static ShardingType shardingType = ShardingType.MASTER_SLAVE;
private static boolean loadConfigFromRegCenter = false;
// private static boolean loadConfigFromRegCenter = true;
private static RegistryCenterType registryCenterType = RegistryCenterType.ZOOKEEPER;
// private static RegistryCenterType registryCenterType = RegistryCenterType.ETCD;
public static void main(final String[] args) throws Exception {
DataSource dataSource = getDataSource(registryCenterType, loadConfigFromRegCenter, shardingType);
CommonService commonService = getCommonService(dataSource);
commonService.initEnvironment();
commonService.processSuccess();
commonService.cleanEnvironment();
closeDataSource(dataSource);
}
private static DataSource getDataSource(final RegistryCenterType registryCenterType, final boolean loadConfigFromRegCenter, final ShardingType shardingType) throws SQLException, IOException {
String yamlFilePath;
switch (shardingType) {
case SHARDING_DATABASES_AND_TABLES:
yamlFilePath = String.format("/META-INF/%s/%s/sharding-databases-tables.yaml", registryCenterType.name().toLowerCase(), loadConfigFromRegCenter ? "cloud" : "local");
return YamlOrchestrationShardingDataSourceFactory.createDataSource(getFile(yamlFilePath));
case MASTER_SLAVE:
yamlFilePath = String.format("/META-INF/%s/%s/master-slave.yaml", registryCenterType.name().toLowerCase(), loadConfigFromRegCenter ? "cloud" : "local");
return YamlOrchestrationMasterSlaveDataSourceFactory.createDataSource(getFile(yamlFilePath));
default:
throw new UnsupportedOperationException(shardingType.name());
}
}
private static File getFile(final String fileName) {
return new File(Thread.currentThread().getClass().getResource(fileName).getFile());
}
private static CommonService getCommonService(final DataSource dataSource) {
return new CommonServiceImpl(new OrderRepositoryImpl(dataSource), new OrderItemRepositoryImpl(dataSource));
}
private static void closeDataSource(final DataSource dataSource) throws Exception {
if (dataSource instanceof AbstractDataSourceAdapter) {
((AbstractDataSourceAdapter) dataSource).close();
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.orchestration.raw.jdbc.config;
import org.apache.shardingsphere.orchestration.reg.api.RegistryCenterConfiguration;
public class RegistryCenterConfigurationUtil {
private static final String ZOOKEEPER_CONNECTION_STRING = "localhost:2181";
private static final String NAMESPACE = "orchestration-java-demo";
private static final String ETCD_CONNECTION_STRING = "http://localhost:2379";
public static RegistryCenterConfiguration getZooKeeperConfiguration() {
RegistryCenterConfiguration result = new RegistryCenterConfiguration();
result.setServerLists(ZOOKEEPER_CONNECTION_STRING);
result.setNamespace(NAMESPACE);
return result;
}
public static RegistryCenterConfiguration getEtcdConfiguration() {
RegistryCenterConfiguration result = new RegistryCenterConfiguration();
result.setServerLists(ETCD_CONNECTION_STRING);
return result;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.orchestration.raw.jdbc.config.cloud;
import io.shardingsphere.example.config.ExampleConfiguration;
import org.apache.shardingsphere.orchestration.config.OrchestrationConfiguration;
import org.apache.shardingsphere.orchestration.reg.api.RegistryCenterConfiguration;
import org.apache.shardingsphere.shardingjdbc.orchestration.api.OrchestrationMasterSlaveDataSourceFactory;
import javax.sql.DataSource;
import java.sql.SQLException;
public final class CloudMasterSlaveConfiguration implements ExampleConfiguration {
private final RegistryCenterConfiguration registryCenterConfig;
public CloudMasterSlaveConfiguration(final RegistryCenterConfiguration registryCenterConfig) {
this.registryCenterConfig = registryCenterConfig;
}
@Override
public DataSource getDataSource() throws SQLException {
return OrchestrationMasterSlaveDataSourceFactory.createDataSource(new OrchestrationConfiguration("orchestration-master-slave-data-source", registryCenterConfig, false));
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.orchestration.raw.jdbc.config.cloud;
import io.shardingsphere.example.config.ExampleConfiguration;
import org.apache.shardingsphere.orchestration.config.OrchestrationConfiguration;
import org.apache.shardingsphere.orchestration.reg.api.RegistryCenterConfiguration;
import org.apache.shardingsphere.shardingjdbc.orchestration.api.OrchestrationShardingDataSourceFactory;
import javax.sql.DataSource;
import java.sql.SQLException;
public final class CloudShardingDatabasesAndTablesConfiguration implements ExampleConfiguration {
private final RegistryCenterConfiguration registryCenterConfig;
public CloudShardingDatabasesAndTablesConfiguration(final RegistryCenterConfiguration registryCenterConfig) {
this.registryCenterConfig = registryCenterConfig;
}
@Override
public DataSource getDataSource() throws SQLException {
return OrchestrationShardingDataSourceFactory.createDataSource(new OrchestrationConfiguration("orchestration-sharding-dbtbl-data-source", registryCenterConfig, false));
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.orchestration.raw.jdbc.config.local;
import io.shardingsphere.example.common.DataSourceUtil;
import io.shardingsphere.example.config.ExampleConfiguration;
import org.apache.shardingsphere.api.config.masterslave.MasterSlaveRuleConfiguration;
import org.apache.shardingsphere.orchestration.config.OrchestrationConfiguration;
import org.apache.shardingsphere.orchestration.reg.api.RegistryCenterConfiguration;
import org.apache.shardingsphere.shardingjdbc.orchestration.api.OrchestrationMasterSlaveDataSourceFactory;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public final class LocalMasterSlaveConfiguration implements ExampleConfiguration {
private final RegistryCenterConfiguration registryCenterConfig;
public LocalMasterSlaveConfiguration(final RegistryCenterConfiguration registryCenterConfig) {
this.registryCenterConfig = registryCenterConfig;
}
@Override
public DataSource getDataSource() throws SQLException {
MasterSlaveRuleConfiguration masterSlaveRuleConfig = new MasterSlaveRuleConfiguration("demo_ds_master_slave", "demo_ds_master", Arrays.asList("demo_ds_slave_0", "demo_ds_slave_1"));
OrchestrationConfiguration orchestrationConfig = new OrchestrationConfiguration("orchestration-master-slave-data-source", registryCenterConfig, true);
return OrchestrationMasterSlaveDataSourceFactory.createDataSource(createDataSourceMap(), masterSlaveRuleConfig, new Properties(), orchestrationConfig);
}
private Map<String, DataSource> createDataSourceMap() {
Map<String, DataSource> result = new HashMap<>();
result.put("demo_ds_master", DataSourceUtil.createDataSource("demo_ds_master"));
result.put("demo_ds_slave_0", DataSourceUtil.createDataSource("demo_ds_slave_0"));
result.put("demo_ds_slave_1", DataSourceUtil.createDataSource("demo_ds_slave_1"));
return result;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.orchestration.raw.jdbc.config.local;
import io.shardingsphere.example.algorithm.PreciseModuloShardingTableAlgorithm;
import io.shardingsphere.example.common.DataSourceUtil;
import io.shardingsphere.example.config.ExampleConfiguration;
import org.apache.shardingsphere.api.config.encryptor.EncryptorConfiguration;
import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.InlineShardingStrategyConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.StandardShardingStrategyConfiguration;
import org.apache.shardingsphere.orchestration.config.OrchestrationConfiguration;
import org.apache.shardingsphere.orchestration.reg.api.RegistryCenterConfiguration;
import org.apache.shardingsphere.shardingjdbc.orchestration.api.OrchestrationShardingDataSourceFactory;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public final class LocalShardingDatabasesAndTablesConfiguration implements ExampleConfiguration {
private final RegistryCenterConfiguration registryCenterConfig;
public LocalShardingDatabasesAndTablesConfiguration(final RegistryCenterConfiguration registryCenterConfig) {
this.registryCenterConfig = registryCenterConfig;
}
@Override
public DataSource getDataSource() throws SQLException {
ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
shardingRuleConfig.getTableRuleConfigs().add(getOrderTableRuleConfiguration());
shardingRuleConfig.getTableRuleConfigs().add(getOrderItemTableRuleConfiguration());
shardingRuleConfig.getTableRuleConfigs().add(getOrderEncryptTableRuleConfiguration());
shardingRuleConfig.getBindingTableGroups().add("t_order, t_order_item, t_order_encrypt");
shardingRuleConfig.setDefaultDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("user_id", "demo_ds_${user_id % 2}"));
shardingRuleConfig.setDefaultTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("order_id", new PreciseModuloShardingTableAlgorithm()));
OrchestrationConfiguration orchestrationConfig = new OrchestrationConfiguration("orchestration-sharding-dbtbl-data-source", registryCenterConfig, true);
return OrchestrationShardingDataSourceFactory.createDataSource(createDataSourceMap(), shardingRuleConfig, new Properties(), orchestrationConfig);
}
private TableRuleConfiguration getOrderTableRuleConfiguration() {
TableRuleConfiguration result = new TableRuleConfiguration("t_order", "demo_ds_${0..1}.t_order_${[0, 1]}");
result.setKeyGeneratorConfig(getKeyGeneratorConfiguration());
return result;
}
private static TableRuleConfiguration getOrderItemTableRuleConfiguration() {
TableRuleConfiguration result = new TableRuleConfiguration("t_order_item", "demo_ds_${0..1}.t_order_item_${[0, 1]}");
result.setEncryptorConfig(new EncryptorConfiguration("MD5", "status", new Properties()));
return result;
}
private static TableRuleConfiguration getOrderEncryptTableRuleConfiguration() {
TableRuleConfiguration result = new TableRuleConfiguration("t_order_encrypt", "demo_ds_${0..1}.t_order_encrypt_${[0, 1]}");
result.setEncryptorConfig(new EncryptorConfiguration("query", "encrypt_id", "query_id", new Properties()));
return result;
}
private Map<String, DataSource> createDataSourceMap() {
Map<String, DataSource> result = new HashMap<>();
result.put("demo_ds_0", DataSourceUtil.createDataSource("demo_ds_0"));
result.put("demo_ds_1", DataSourceUtil.createDataSource("demo_ds_1"));
return result;
}
private static KeyGeneratorConfiguration getKeyGeneratorConfiguration() {
return new KeyGeneratorConfiguration("SNOWFLAKE", "order_id", new Properties());
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.orchestration.raw.jdbc.config.local;
import io.shardingsphere.example.common.DataSourceUtil;
import io.shardingsphere.example.config.ExampleConfiguration;
import org.apache.shardingsphere.api.config.encryptor.EncryptorConfiguration;
import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.InlineShardingStrategyConfiguration;
import org.apache.shardingsphere.orchestration.config.OrchestrationConfiguration;
import org.apache.shardingsphere.orchestration.reg.api.RegistryCenterConfiguration;
import org.apache.shardingsphere.shardingjdbc.orchestration.api.OrchestrationShardingDataSourceFactory;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public final class LocalShardingDatabasesConfiguration implements ExampleConfiguration {
private final RegistryCenterConfiguration registryCenterConfig;
public LocalShardingDatabasesConfiguration(final RegistryCenterConfiguration registryCenterConfig) {
this.registryCenterConfig = registryCenterConfig;
}
@Override
public DataSource getDataSource() throws SQLException {
ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
shardingRuleConfig.getTableRuleConfigs().add(getOrderTableRuleConfiguration());
shardingRuleConfig.getTableRuleConfigs().add(getOrderItemTableRuleConfiguration());
shardingRuleConfig.getTableRuleConfigs().add(getOrderEncryptTableRuleConfiguration());
shardingRuleConfig.getBindingTableGroups().add("t_order, t_order_item, t_order_encrypt");
shardingRuleConfig.setDefaultDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("user_id", "demo_ds_${user_id % 2}"));
OrchestrationConfiguration orchestrationConfig = new OrchestrationConfiguration("orchestration-sharding-db-data-source", registryCenterConfig, true);
return OrchestrationShardingDataSourceFactory.createDataSource(createDataSourceMap(), shardingRuleConfig, new Properties(), orchestrationConfig);
}
private TableRuleConfiguration getOrderTableRuleConfiguration() {
TableRuleConfiguration result = new TableRuleConfiguration("t_order");
result.setKeyGeneratorConfig(getKeyGeneratorConfiguration());
return result;
}
private static TableRuleConfiguration getOrderItemTableRuleConfiguration() {
TableRuleConfiguration result = new TableRuleConfiguration("t_order_item");
result.setEncryptorConfig(new EncryptorConfiguration("MD5", "status", new Properties()));
return result;
}
private static TableRuleConfiguration getOrderEncryptTableRuleConfiguration() {
TableRuleConfiguration result = new TableRuleConfiguration("t_order_encrypt");
result.setEncryptorConfig(new EncryptorConfiguration("query", "encrypt_id", "query_id", new Properties()));
return result;
}
private Map<String, DataSource> createDataSourceMap() {
Map<String, DataSource> result = new HashMap<>();
result.put("demo_ds_0", DataSourceUtil.createDataSource("demo_ds_0"));
result.put("demo_ds_1", DataSourceUtil.createDataSource("demo_ds_1"));
return result;
}
private static KeyGeneratorConfiguration getKeyGeneratorConfiguration() {
return new KeyGeneratorConfiguration("SNOWFLAKE", "order_id", new Properties());
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.orchestration.raw.jdbc.config.local;
import com.google.common.collect.Lists;
import io.shardingsphere.example.algorithm.PreciseModuloShardingDatabaseAlgorithm;
import io.shardingsphere.example.algorithm.PreciseModuloShardingTableAlgorithm;
import io.shardingsphere.example.common.DataSourceUtil;
import io.shardingsphere.example.config.ExampleConfiguration;
import org.apache.shardingsphere.api.config.encryptor.EncryptorConfiguration;
import org.apache.shardingsphere.api.config.masterslave.MasterSlaveRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.StandardShardingStrategyConfiguration;
import org.apache.shardingsphere.orchestration.config.OrchestrationConfiguration;
import org.apache.shardingsphere.orchestration.reg.api.RegistryCenterConfiguration;
import org.apache.shardingsphere.shardingjdbc.orchestration.api.OrchestrationShardingDataSourceFactory;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public final class LocalShardingMasterSlaveConfiguration implements ExampleConfiguration {
private final RegistryCenterConfiguration registryCenterConfig;
public LocalShardingMasterSlaveConfiguration(final RegistryCenterConfiguration registryCenterConfig) {
this.registryCenterConfig = registryCenterConfig;
}
@Override
public DataSource getDataSource() throws SQLException {
ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
shardingRuleConfig.getTableRuleConfigs().add(getOrderTableRuleConfiguration());
shardingRuleConfig.getTableRuleConfigs().add(getOrderItemTableRuleConfiguration());
shardingRuleConfig.getTableRuleConfigs().add(getOrderEncryptTableRuleConfiguration());
shardingRuleConfig.getBindingTableGroups().add("t_order, t_order_item, t_order_encrypt");
shardingRuleConfig.setDefaultDatabaseShardingStrategyConfig(new StandardShardingStrategyConfiguration("user_id", new PreciseModuloShardingDatabaseAlgorithm()));
shardingRuleConfig.setDefaultTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("order_id", new PreciseModuloShardingTableAlgorithm()));
shardingRuleConfig.setMasterSlaveRuleConfigs(getMasterSlaveRuleConfigurations());
OrchestrationConfiguration orchestrationConfig = new OrchestrationConfiguration("orchestration-sharding-master-slave-data-source", registryCenterConfig, true);
return OrchestrationShardingDataSourceFactory.createDataSource(createDataSourceMap(), shardingRuleConfig, new Properties(), orchestrationConfig);
}
private TableRuleConfiguration getOrderTableRuleConfiguration() {
TableRuleConfiguration result = new TableRuleConfiguration("t_order", "ds_${0..1}.t_order_${[0, 1]}");
result.setKeyGeneratorConfig(getKeyGeneratorConfiguration());
return result;
}
private static TableRuleConfiguration getOrderItemTableRuleConfiguration() {
TableRuleConfiguration result = new TableRuleConfiguration("t_order_item", "ds_${0..1}.t_order_item_${[0, 1]}");
result.setEncryptorConfig(new EncryptorConfiguration("MD5", "status", new Properties()));
return result;
}
private static TableRuleConfiguration getOrderEncryptTableRuleConfiguration() {
TableRuleConfiguration result = new TableRuleConfiguration("t_order_encrypt", "ds_${0..1}.t_order_encrypt_${[0, 1]}");
result.setEncryptorConfig(new EncryptorConfiguration("query", "encrypt_id", "query_id", new Properties()));
return result;
}
private List<MasterSlaveRuleConfiguration> getMasterSlaveRuleConfigurations() {
MasterSlaveRuleConfiguration masterSlaveRuleConfig1 = new MasterSlaveRuleConfiguration("ds_0", "demo_ds_master_0", Arrays.asList("demo_ds_master_0_slave_0", "demo_ds_master_0_slave_1"));
MasterSlaveRuleConfiguration masterSlaveRuleConfig2 = new MasterSlaveRuleConfiguration("ds_1", "demo_ds_master_1", Arrays.asList("demo_ds_master_1_slave_0", "demo_ds_master_1_slave_1"));
return Lists.newArrayList(masterSlaveRuleConfig1, masterSlaveRuleConfig2);
}
private Map<String, DataSource> createDataSourceMap() {
final Map<String, DataSource> result = new HashMap<>();
result.put("demo_ds_master_0", DataSourceUtil.createDataSource("demo_ds_master_0"));
result.put("demo_ds_master_0_slave_0", DataSourceUtil.createDataSource("demo_ds_master_0_slave_0"));
result.put("demo_ds_master_0_slave_1", DataSourceUtil.createDataSource("demo_ds_master_0_slave_1"));
result.put("demo_ds_master_1", DataSourceUtil.createDataSource("demo_ds_master_1"));
result.put("demo_ds_master_1_slave_0", DataSourceUtil.createDataSource("demo_ds_master_1_slave_0"));
result.put("demo_ds_master_1_slave_1", DataSourceUtil.createDataSource("demo_ds_master_1_slave_1"));
return result;
}
private static KeyGeneratorConfiguration getKeyGeneratorConfiguration() {
return new KeyGeneratorConfiguration("SNOWFLAKE", "order_id", new Properties());
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.orchestration.raw.jdbc.config.local;
import io.shardingsphere.example.algorithm.PreciseModuloShardingTableAlgorithm;
import io.shardingsphere.example.common.DataSourceUtil;
import io.shardingsphere.example.config.ExampleConfiguration;
import org.apache.shardingsphere.api.config.encryptor.EncryptorConfiguration;
import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.StandardShardingStrategyConfiguration;
import org.apache.shardingsphere.orchestration.config.OrchestrationConfiguration;
import org.apache.shardingsphere.orchestration.reg.api.RegistryCenterConfiguration;
import org.apache.shardingsphere.shardingjdbc.orchestration.api.OrchestrationShardingDataSourceFactory;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public final class LocalShardingTablesConfiguration implements ExampleConfiguration {
private final RegistryCenterConfiguration registryCenterConfig;
public LocalShardingTablesConfiguration(final RegistryCenterConfiguration registryCenterConfig) {
this.registryCenterConfig = registryCenterConfig;
}
@Override
public DataSource getDataSource() throws SQLException {
ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
shardingRuleConfig.getTableRuleConfigs().add(getOrderTableRuleConfiguration());
shardingRuleConfig.getTableRuleConfigs().add(getOrderItemTableRuleConfiguration());
shardingRuleConfig.getTableRuleConfigs().add(getOrderEncryptTableRuleConfiguration());
shardingRuleConfig.getBindingTableGroups().add("t_order, t_order_item, t_order_encrypt");
shardingRuleConfig.setDefaultTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("order_id", new PreciseModuloShardingTableAlgorithm()));
OrchestrationConfiguration orchestrationConfig = new OrchestrationConfiguration("orchestration-sharding-tbl-data-source", registryCenterConfig, true);
return OrchestrationShardingDataSourceFactory.createDataSource(createDataSourceMap(), shardingRuleConfig, new Properties(), orchestrationConfig);
}
private TableRuleConfiguration getOrderTableRuleConfiguration() {
TableRuleConfiguration result = new TableRuleConfiguration("t_order", "demo_ds.t_order_${[0, 1]}");
result.setKeyGeneratorConfig(getKeyGeneratorConfiguration());
return result;
}
private static TableRuleConfiguration getOrderItemTableRuleConfiguration() {
TableRuleConfiguration result = new TableRuleConfiguration("t_order_item", "demo_ds.t_order_item_${[0, 1]}");
result.setEncryptorConfig(new EncryptorConfiguration("MD5", "status", new Properties()));
return result;
}
private static TableRuleConfiguration getOrderEncryptTableRuleConfiguration() {
TableRuleConfiguration result = new TableRuleConfiguration("t_order_encrypt", "demo_ds.t_order_encrypt_${[0, 1]}");
result.setEncryptorConfig(new EncryptorConfiguration("query", "encrypt_id", "query_id", new Properties()));
return result;
}
private Map<String, DataSource> createDataSourceMap() {
Map<String, DataSource> result = new HashMap<>();
result.put("demo_ds", DataSourceUtil.createDataSource("demo_ds"));
return result;
}
private static KeyGeneratorConfiguration getKeyGeneratorConfiguration() {
return new KeyGeneratorConfiguration("SNOWFLAKE", "order_id", new Properties());
}
}
orchestration:
name: demo_yaml_ds_ms
overwrite: false
registry:
serverLists: localhost:2181
namespace: orchestration-yaml-demo
orchestration:
name: demo_yaml_ds_sharding
overwrite: false
registry:
serverLists: localhost:2181
namespace: orchestration-yaml-demo
dataSources:
ds_master: !!com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.jdbc.Driver
jdbcUrl: jdbc:mysql://localhost:3306/demo_ds_master
username: root
password:
ds_slave_0: !!com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.jdbc.Driver
jdbcUrl: jdbc:mysql://localhost:3306/demo_ds_slave_0
username: root
password:
ds_slave_1: !!com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.jdbc.Driver
jdbcUrl: jdbc:mysql://localhost:3306/demo_ds_slave_1
username: root
password:
masterSlaveRule:
name: ds_ms
masterDataSourceName: ds_master
slaveDataSourceNames: [ds_slave_0, ds_slave_1]
props:
sql.show: true
orchestration:
name: demo_yaml_ds_ms
overwrite: true
registry:
serverLists: localhost:2181
namespace: orchestration-yaml-demo
dataSources:
ds_0: !!com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.jdbc.Driver
jdbcUrl: jdbc:mysql://localhost:3306/demo_ds_0
username: root
password:
ds_1: !!com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.jdbc.Driver
jdbcUrl: jdbc:mysql://localhost:3306/demo_ds_1
username: root
password:
shardingRule:
tables:
t_order:
actualDataNodes: ds_${0..1}.t_order_${0..1}
tableStrategy:
inline:
shardingColumn: order_id
algorithmExpression: t_order_${order_id % 2}
keyGenerator:
column: order_id
type: SNOWFLAKE
t_order_item:
actualDataNodes: ds_${0..1}.t_order_item_${0..1}
tableStrategy:
inline:
shardingColumn: order_id
algorithmExpression: t_order_item_${order_id % 2}
bindingTables:
- t_order,t_order_item
defaultDatabaseStrategy:
inline:
shardingColumn: user_id
algorithmExpression: ds_${user_id % 2}
defaultTableStrategy:
none:
props:
sql.show: true
orchestration:
name: demo_yaml_ds_sharding
overwrite: true
registry:
serverLists: localhost:2181
namespace: orchestration-yaml-demo
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one or more
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~ The ASF licenses this file to You under the Apache License, Version 2.0
~ (the "License"); you may not use this file except in compliance with
~ the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<configuration>
<property name="log.context.name" value="sharding-orchestration-zookeeper-raw-jdbc-quickstart" />
<property name="log.charset" value="UTF-8" />
<property name="log.pattern" value="[%-5level] %date --%thread-- [%logger] %msg %n" />
<contextName>${log.context.name}</contextName>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder charset="${log.charset}">
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="STDOUT" />
</root>
</configuration>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.shardingsphere</groupId>
<artifactId>orchestration-example</artifactId>
<version>4.0.0-RC1-SNAPSHOT</version>
</parent>
<artifactId>orchestration-spring-boot-example</artifactId>
<dependencies>
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>repository-jpa</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-orchestration-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-orchestration-reg-zookeeper-curator</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>io.shardingsphere</groupId>-->
<!--<artifactId>sharding-orchestration-reg-etcd</artifactId>-->
<!--</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
</project>
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.orchestration.spring.boot;
import io.shardingsphere.example.common.jpa.service.JPACommonService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan("io.shardingsphere.example.common.jpa")
@EntityScan(basePackages = "io.shardingsphere.example.common.jpa.entity")
@SpringBootApplication(exclude = JtaAutoConfiguration.class)
public class SpringBootExample {
public static void main(final String[] args) {
try (ConfigurableApplicationContext applicationContext = SpringApplication.run(SpringBootExample.class, args)) {
JPACommonService commonService = applicationContext.getBean(JPACommonService.class);
commonService.processSuccess();
}
}
}
sharding.jdbc.config.orchestration.name=demo_spring_boot_ds_ms
sharding.jdbc.config.orchestration.overwrite=false
sharding.jdbc.config.orchestration.registry.server-lists=http://localhost:2379
sharding.jdbc.config.orchestration.name=demo_spring_boot_ds_sharding
sharding.jdbc.config.orchestration.overwrite=false
sharding.jdbc.config.orchestration.registry.server-lists=http://localhost:2379
sharding.jdbc.config.orchestration.name=demo_spring_boot_ds_ms
sharding.jdbc.config.orchestration.overwrite=false
sharding.jdbc.config.orchestration.registry.server-lists=localhost:2181
sharding.jdbc.config.orchestration.registry.namespace=orchestration-spring-boot-demo
sharding.jdbc.config.orchestration.name=demo_spring_boot_ds_sharding
sharding.jdbc.config.orchestration.overwrite=false
sharding.jdbc.config.orchestration.registry.server-lists=localhost:2181
sharding.jdbc.config.orchestration.registry.namespace=orchestration-spring-boot-demo
sharding.jdbc.datasource.names=ds_master,ds_slave_0,ds_slave_1
sharding.jdbc.datasource.ds_master.type=com.zaxxer.hikari.HikariDataSource
sharding.jdbc.datasource.ds_master.driver-class-name=com.mysql.jdbc.Driver
sharding.jdbc.datasource.ds_master.jdbc-url=jdbc:mysql://localhost:3306/demo_ds_master?serverTimezone=UTC&useSSL=false
sharding.jdbc.datasource.ds_master.username=root
sharding.jdbc.datasource.ds_master.password=
sharding.jdbc.datasource.ds_slave_0.type=com.zaxxer.hikari.HikariDataSource
sharding.jdbc.datasource.ds_slave_0.driver-class-name=com.mysql.jdbc.Driver
sharding.jdbc.datasource.ds_slave_0.jdbc-url=jdbc:mysql://localhost:3306/demo_ds_slave_0?serverTimezone=UTC&useSSL=false
sharding.jdbc.datasource.ds_slave_0.username=root
sharding.jdbc.datasource.ds_slave_0.password=
sharding.jdbc.datasource.ds_slave_1.type=com.zaxxer.hikari.HikariDataSource
sharding.jdbc.datasource.ds_slave_1.driver-class-name=com.mysql.jdbc.Driver
sharding.jdbc.datasource.ds_slave_1.jdbc-url=jdbc:mysql://localhost:3306/demo_ds_slave_1?serverTimezone=UTC&useSSL=false
sharding.jdbc.datasource.ds_slave_1.username=root
sharding.jdbc.datasource.ds_slave_1.password=
sharding.jdbc.config.masterslave.load-balance-algorithm-type=round_robin
sharding.jdbc.config.masterslave.name=ds_ms
sharding.jdbc.config.masterslave.master-data-source-name=ds_master
sharding.jdbc.config.masterslave.slave-data-source-names=ds_slave_0,ds_slave_1
sharding.jdbc.config.orchestration.name=demo_spring_boot_ds_ms
sharding.jdbc.config.orchestration.overwrite=true
sharding.jdbc.config.orchestration.registry.server-lists=http://localhost:2379
sharding.jdbc.datasource.names=ds_0,ds_1
sharding.jdbc.datasource.ds_0.type=com.zaxxer.hikari.HikariDataSource
sharding.jdbc.datasource.ds_0.driver-class-name=com.mysql.jdbc.Driver
sharding.jdbc.datasource.ds_0.jdbc-url=jdbc:mysql://localhost:3306/demo_ds_0
sharding.jdbc.datasource.ds_0.username=root
sharding.jdbc.datasource.ds_0.password=
sharding.jdbc.datasource.ds_0.max-active=16
sharding.jdbc.datasource.ds_1.type=com.zaxxer.hikari.HikariDataSource
sharding.jdbc.datasource.ds_1.driver-class-name=com.mysql.jdbc.Driver
sharding.jdbc.datasource.ds_1.jdbc-url=jdbc:mysql://localhost:3306/demo_ds_1
sharding.jdbc.datasource.ds_1.username=root
sharding.jdbc.datasource.ds_1.password=
sharding.jdbc.datasource.ds_1.max-active=16
sharding.jdbc.config.sharding.default-database-strategy.inline.sharding-column=user_id
sharding.jdbc.config.sharding.default-database-strategy.inline.algorithm-expression=ds_$->{user_id % 2}
sharding.jdbc.config.sharding.tables.t_order.actual-data-nodes=ds_$->{0..1}.t_order_$->{0..1}
sharding.jdbc.config.sharding.tables.t_order.table-strategy.inline.sharding-column=order_id
sharding.jdbc.config.sharding.tables.t_order.table-strategy.inline.algorithm-expression=t_order_$->{order_id % 2}
sharding.jdbc.config.sharding.tables.t_order.key-generator.column=order_id
sharding.jdbc.config.sharding.tables.t_order.key-generator.type=SNOWFLAKE
sharding.jdbc.config.sharding.tables.t_order_item.actual-data-nodes=ds_$->{0..1}.t_order_item_$->{0..1}
sharding.jdbc.config.sharding.tables.t_order_item.table-strategy.inline.sharding-column=order_id
sharding.jdbc.config.sharding.tables.t_order_item.table-strategy.inline.algorithm-expression=t_order_item_$->{order_id % 2}
sharding.jdbc.config.sharding.tables.t_order_item.key-generator.column=order_item_id
sharding.jdbc.config.sharding.tables.t_order_item.key-generator.type=SNOWFLAKE
sharding.jdbc.config.orchestration.name=demo_spring_boot_ds_sharding
sharding.jdbc.config.orchestration.overwrite=true
sharding.jdbc.config.orchestration.registry.server-lists=http://localhost:2379
sharding.jdbc.config.orchestration.registry.timeToLiveSeconds=600
sharding.jdbc.datasource.names=ds_master,ds_slave_0,ds_slave_1
sharding.jdbc.datasource.ds_master.type=com.zaxxer.hikari.HikariDataSource
sharding.jdbc.datasource.ds_master.driver-class-name=com.mysql.jdbc.Driver
sharding.jdbc.datasource.ds_master.jdbc-url=jdbc:mysql://localhost:3306/demo_ds_master
sharding.jdbc.datasource.ds_master.username=root
sharding.jdbc.datasource.ds_master.password=
sharding.jdbc.datasource.ds_slave_0.type=com.zaxxer.hikari.HikariDataSource
sharding.jdbc.datasource.ds_slave_0.driver-class-name=com.mysql.jdbc.Driver
sharding.jdbc.datasource.ds_slave_0.jdbc-url=jdbc:mysql://localhost:3306/demo_ds_slave_0
sharding.jdbc.datasource.ds_slave_0.username=root
sharding.jdbc.datasource.ds_slave_0.password=
sharding.jdbc.datasource.ds_slave_1.type=com.zaxxer.hikari.HikariDataSource
sharding.jdbc.datasource.ds_slave_1.driver-class-name=com.mysql.jdbc.Driver
sharding.jdbc.datasource.ds_slave_1.jdbc-url=jdbc:mysql://localhost:3306/demo_ds_slave_1
sharding.jdbc.datasource.ds_slave_1.username=root
sharding.jdbc.datasource.ds_slave_1.password=
sharding.jdbc.config.masterslave.load-balance-algorithm-type=round_robin
sharding.jdbc.config.masterslave.name=ds_ms
sharding.jdbc.config.masterslave.master-data-source-name=ds_master
sharding.jdbc.config.masterslave.slave-data-source-names=ds_slave_0,ds_slave_1
sharding.jdbc.config.orchestration.name=demo_spring_boot_ds_ms
sharding.jdbc.config.orchestration.overwrite=true
sharding.jdbc.config.orchestration.registry.server-lists=localhost:2181
sharding.jdbc.config.orchestration.registry.namespace=orchestration-spring-boot-demo
sharding.jdbc.datasource.names=ds_0,ds_1
sharding.jdbc.datasource.ds_0.type=com.zaxxer.hikari.HikariDataSource
sharding.jdbc.datasource.ds_0.driver-class-name=com.mysql.jdbc.Driver
sharding.jdbc.datasource.ds_0.jdbc-url=jdbc:mysql://localhost:3306/demo_ds_0
sharding.jdbc.datasource.ds_0.username=root
sharding.jdbc.datasource.ds_0.password=
sharding.jdbc.datasource.ds_0.max-active=16
sharding.jdbc.datasource.ds_1.type=com.zaxxer.hikari.HikariDataSource
sharding.jdbc.datasource.ds_1.driver-class-name=com.mysql.jdbc.Driver
sharding.jdbc.datasource.ds_1.jdbc-url=jdbc:mysql://localhost:3306/demo_ds_1
sharding.jdbc.datasource.ds_1.username=root
sharding.jdbc.datasource.ds_1.password=
sharding.jdbc.datasource.ds_1.max-active=16
sharding.jdbc.config.sharding.default-database-strategy.inline.sharding-column=user_id
sharding.jdbc.config.sharding.default-database-strategy.inline.algorithm-expression=ds_$->{user_id % 2}
sharding.jdbc.config.sharding.tables.t_order.actual-data-nodes=ds_$->{0..1}.t_order_$->{0..1}
sharding.jdbc.config.sharding.tables.t_order.table-strategy.inline.sharding-column=order_id
sharding.jdbc.config.sharding.tables.t_order.table-strategy.inline.algorithm-expression=t_order_$->{order_id % 2}
sharding.jdbc.config.sharding.tables.t_order.key-generator.column=order_id
sharding.jdbc.config.sharding.tables.t_order.key-generator.type=SNOWFLAKE
sharding.jdbc.config.sharding.tables.t_order_item.actual-data-nodes=ds_$->{0..1}.t_order_item_$->{0..1}
sharding.jdbc.config.sharding.tables.t_order_item.table-strategy.inline.sharding-column=order_id
sharding.jdbc.config.sharding.tables.t_order_item.table-strategy.inline.algorithm-expression=t_order_item_$->{order_id % 2}
sharding.jdbc.config.sharding.tables.t_order_item.key-generator.column=order_item_id
sharding.jdbc.config.sharding.tables.t_order_item.key-generator.type=SNOWFLAKE
sharding.jdbc.config.orchestration.name=demo_spring_boot_ds_sharding
sharding.jdbc.config.orchestration.overwrite=true
sharding.jdbc.config.orchestration.registry.server-lists=localhost:2181
sharding.jdbc.config.orchestration.registry.namespace=orchestration-spring-boot-demo
spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.show_sql=false
spring.profiles.active=local-zookeeper-sharding-databases-tables
#spring.profiles.active=local-zookeeper-master-slave
#spring.profiles.active=local-etcd-sharding-databases-tables
#spring.profiles.active=local-etcd-master-slave
#spring.profiles.active=cloud-zookeeper-sharding-databases-tables
#spring.profiles.active=cloud-zookeeper-master-slave
#spring.profiles.active=cloud-etcd-sharding-databases-tables
#spring.profiles.active=cloud-etcd-master-slave
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.shardingsphere</groupId>
<artifactId>orchestration-example</artifactId>
<version>4.0.0-RC1-SNAPSHOT</version>
</parent>
<artifactId>orchestration-spring-namespace-example</artifactId>
<dependencies>
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>config-utility</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>repository-mybatis</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-namespace</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-orchestration-spring-namespace</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-orchestration-reg-zookeeper-curator</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>io.shardingsphere</groupId>-->
<!--<artifactId>sharding-orchestration-reg-etcd</artifactId>-->
<!--</dependency>-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
</dependencies>
</project>
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shardingsphere.example.orchestration.spring.namespace;
import io.shardingsphere.example.common.mybatis.service.SpringPojoService;
import io.shardingsphere.example.type.RegistryCenterType;
import io.shardingsphere.example.type.ShardingType;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringNamespaceExample {
private static ShardingType shardingType = ShardingType.SHARDING_DATABASES_AND_TABLES;
// private static ShardingType shardingType = ShardingType.MASTER_SLAVE;
private static boolean loadConfigFromRegCenter = false;
// private static boolean loadConfigFromRegCenter = true;
private static RegistryCenterType registryCenterType = RegistryCenterType.ZOOKEEPER;
// private static RegistryCenterType registryCenterType = RegistryCenterType.ETCD;
public static void main(final String[] args) {
try (ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext(getApplicationFile())) {
SpringPojoService commonService = applicationContext.getBean(SpringPojoService.class);
commonService.initEnvironment();
commonService.processSuccess();
commonService.cleanEnvironment();
}
}
private static String getApplicationFile() {
switch (shardingType) {
case SHARDING_DATABASES_AND_TABLES:
return String.format("META-INF/%s/%s/application-sharding-databases-tables.xml", registryCenterType.name().toLowerCase(), loadConfigFromRegCenter ? "cloud" : "local");
case MASTER_SLAVE:
return String.format("META-INF/%s/%s/application-master-slave.xml", registryCenterType.name().toLowerCase(), loadConfigFromRegCenter ? "cloud" : "local");
default:
throw new UnsupportedOperationException(shardingType.name());
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:orchestraion="http://shardingsphere.apache.org/schema/shardingsphere/orchestration"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://shardingsphere.apache.org/schema/shardingsphere/orchestration
http://shardingsphere.apache.org/schema/shardingsphere/orchestration/orchestration.xsd">
<orchestraion:registry-center id="regCenter" server-lists="http://localhost:2379" operation-timeout-milliseconds="3000" max-retries="3" />
</beans>
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册