关于springboot:个人学习系列-Spring-Boot-ShardingSphere-JPA-实现读写分离

53次阅读

共计 4774 个字符,预计需要花费 12 分钟才能阅读完成。

最近想要学习一下分库分表,可是分库分表之前能够先用数据库的读写拆散来过渡一下,当然这还须要主从服务器来配合。明天就先写数据库的读写拆散,当前再介绍主从服务器。。。

Mysql

1. 新建三个数据库

CREATE DATABASE database0;
USE database0;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`(id bigint(64) not null auto_increment,
    city varchar(20) not null,
    name varchar(20) not null,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE DATABASE database1;
USE database1;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`(id bigint(64) not null auto_increment,
    city varchar(20) not null,
    name varchar(20) not null,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `database1`.`user`(`id`, `city`, `name`) VALUES (001, '青岛', '测试库 1');

CREATE DATABASE database2;
USE database2;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`(id bigint(64) not null auto_increment,
    city varchar(20) not null,
    name varchar(20) not null,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `database2`.`user`(`id`, `city`, `name`) VALUES (002, '胶州', '测试库 2');

2. 新建 springboot 我的项目

2.1 pom.xml
    <!-- web 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- mybatis 依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>

        <!-- mysql 依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!-- druid 数据库连接池依赖 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.23</version>
        </dependency>

        <!-- ShardingSphere 依赖 -->
        <dependency>
            <groupId>io.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
            <version>3.1.0</version>
        </dependency>

        <!-- jap 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
2.2 application.yml
server: # 端口号
  port: 8888
sharding:
  jdbc:
    dataSource:
      names: db-test0,db-test1,db-test2
      # 配置主库
      db-test0:
        type: com.alibaba.druid.pool.DruidDataSource
        driverClassName: com.mysql.jdbc.Driver
        url: jdbc:mysql://ip:3306/database0?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT
        username: 账户
        password: 明码
        #最大连接数
        maxPoolSize: 20
      db-test1: # 配置第一个从库
        type: com.alibaba.druid.pool.DruidDataSource
        driverClassName: com.mysql.jdbc.Driver
        url: jdbc:mysql://ip:3306/database1?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT
        username: 账户
        password: 明码
        maxPoolSize: 20
      db-test2: # 配置第二个从库
        type: com.alibaba.druid.pool.DruidDataSource
        driverClassName: com.mysql.jdbc.Driver
        url: jdbc:mysql://ip:3306/database2?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT
        username: 账户
        password: 明码
        maxPoolSize: 20
    config:
      masterslave: # 配置读写拆散
        load-balance-algorithm-type: round_robin # 配置从库抉择策略,提供轮询与随机,这里抉择用轮询 //random 随机 //round_robin 轮询
        name: db1s2
        master-data-source-name: db-test0
        slave-data-source-names: db-test1,db-test2
    props:
      sql:
        show: true # 开启 SQL 显示,默认值: false,留神:仅配置读写拆散时不会打印日志!!!spring:
  main:
    allow-bean-definition-overriding: true # 容许重名的 bean 能够被笼罩
  jpa:
    hibernate:
      ddl-auto: update # 每次运行程序,没有表格会新建表格,表内有数据不会清空,只会更新
      naming: # 驼峰命名法
        physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
    show-sql: true # 打印 sql

2.3 新建 User 实体类

/**
 * 实体类
 *
 * @author zhouzhaodong
 */
@Entity
@Table(name = "user")
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String city;

    private String name;

    public Long getId() {return id;}

    public void setId(Long id) {this.id = id;}

    public String getCity() {return city;}

    public void setCity(String city) {this.city = city;}

    public String getName() {return name;}

    public void setName(String name) {this.name = name;}
}

2.4 新建 UserRepository

/**
 * 数据拜访层
 *
 * @author zhouzhaodong
 */
@Repository
public interface UserRepository extends JpaRepository<User, Long> {}

2.5 新建服务层 UserService

/**
 * 服务层
 *
 * @author zhouzhaodong
 */
public interface UserService {

    /**
     * 新增
     *
     * @param user
     * @return
     */
    User addUser(User user);

    /**
     * 查问所有
     *
     * @return
     */
    List<User> list();}

2.6 新建服务层实现类 UserServiceImpl

/**
 * 服务层实现类
 *
 * @author zhouzhaodong
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserRepository userRepository;

    @Override
    public User addUser(User user) {

        // 强制路由主库
//        HintManager.getInstance().setMasterRouteOnly();
        return userRepository.save(user);
    }

    @Override
    public List<User> list() {return userRepository.findAll();
    }
}

2.7 新建管制层 UserController

/**
 * 管制层
 *
 * @author zhouzhaodong
 */
@RestController
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("/users")
    public Object list() {return userService.list();
    }

    @PostMapping("/add")
    public Object add(String name, String city) {User user = new User();
        user.setCity(city);
        user.setName(name);
        return userService.addUser(user);
    }

}

2.8 启动类不须要任何操作

3. 启动我的项目进行测试即可

3.1 第一次拜访 localhost:8888/users

3.2 第二次拜访 localhost:8888/users

发现切换查询数据库了,胜利了!

3.3 存储数据

查看数据库会发现只有主库进行了新增,如果配置主从关系的话,从库也会进行新增的。不过咱们还没有进行配置。。。

好了,明天的教程就完结了!!!

集体博客

http://www.zhouzhaodong.xyz

源码地址:

https://github.com/zhouzhaodo…

正文完
 0