垂直分库
垂直分库是指按照业务将表进行分类,分布到不同的数据库上面,每个库可以放在不同的服务器上, 它的核心理念是专库专用.
在使用微服务架构时,业务切割得足够独立,数据也会按照业务切分,保证业务数据隔离,大大提升了数据库的吞吐能力。
1. 创建数据库 导入依赖
CREATE DATABASE lg_user CHARACTER SET 'utf8';
DROP TABLE IF EXISTS users;
CREATE TABLE users (
id BIGINT(20) PRIMARY KEY,
username VARCHAR(20) ,
phone VARCHAR(11),
STATUS VARCHAR(11)
);
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.0.0-RC1</version>
</dependency>
2. 规则配置
- 配置数据源信息
spring.shardingsphere.datasource.names = db1
spring.shardingsphere.datasource.db1.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.db1.driver-class-name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.db1.url = jdbc:mysql://localhost:3306/lg_user?characterEncoding=UTF-8&useSSL=false
spring.shardingsphere.datasource.db1.username = root
spring.shardingsphere.datasource.db1.password = 123456
- 配置数据节点
spring.shardingsphere.sharding.tables.users.actual-data-nodes = db$->{3}.users
spring.shardingsphere.sharding.tables.users.table-strategy.inline.sharding-column = id
spring.shardingsphere.sharding.tables.users.table-strategy.inline.algorithm-expression = users
3. 测试插入与查询
package com.lagou.dao;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
@Mapper
@Component
public interface UsersDao {
/**
* 新增用户
* */
@Insert("insert into users(id,username,phone,status) values(#{id},#{username},#{phone},#{status})")
int insertUser(@Param("id") Long id, @Param("username") String username, @Param("phone") String phone,
@Param("status") String status);
/**
* 查询用户
* */
@Select({"<script>"+
"select * from users u where u.id in " +
"<foreach collection='userIds' item='id' open='(' separator = ',' close=')'>#{id}</foreach>"
+"</script>"})
List<Map> findUserByIds(@Param("userIds") List<Long> userIds);
}
测试
package com.lagou.dao;
import com.lagou.RunBoot;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RunBoot.class)
public class UsersDaoTest {
@Autowired
UsersDao usersDao;
@Test
public void testInsert(){
for (int i = 0; i < 10; i++) {
Long id = i+100L;
usersDao.insertUser(id,"药水"+i, "13555556666","1");
}
}
@Test
public void testFindUser(){
List<Long> ids = new ArrayList<>();
ids.add(101L);
ids.add(102L);
List<Map> list = usersDao.findUserByIds(ids);
System.out.println(list);
}
}