MyBatis uses MyCat to achieve a simple idea of multi-tenancy

The multi-tenancy in this article is implemented based on multiple databases, and the data is isolated through different databases.

MyCat Basic Configuration

First, multiple databases are configured for multi-tenancy, and multiple schemas are configured in MyCat's schema.xml. 
schema

A user is configured in server.xml: 
write picture description here

Later, MyCat annotations (that is, annotations) will be used to point operations to different databases according to different identifiers.

The filter identifies the request matching the corresponding database

There are many ways to distinguish between logos. The simplest one is used below, which is identified by different second-level domain names. The information corresponding to the second-level domain name and the database can be stored in the global library or the public library, and can also be configured by a simple configuration file, but the following code is only for demonstration, so the configuration information is hard-coded in the code.

Suppose there are the following second-level domain names, which correspond to different databases:

  1. ui1.mybatis.tk :UI1
  2. About.com : UI2
  3. ui3.mybatis.tk:UI3

Through the filter, set the database used by the current request according to the request address when the user requests: 
write picture description here

This code is just a very simple judgment, setting different databases according to different strings. A static thread-local variable is used to store database information.

Rewrite MyBatis' MappedStatement to simply implement MyCat annotations

When using MyBatis and the database to operate, all executed sql is obtained through MappedStatement. Although the sql can also be annotated through interceptors, it is a bit complicated to implement. It's much easier by overriding MappedStatement, but you also need to make sure that the overridden class replaces the default one.

Rewriting is very simple, just modify the original  getBoundSql method:

write picture description here

This code is to modify the sql and add it before returning to BoundSql  /*!mycat:schema=数据库*/. The specific database is obtained from the static method of the filter, because each request will go through the filter ( specially, if it is a task-type call, it does not need to go through the filter. , in this case, you need to deal with the binding of the database when the task is executed, which needs to be implemented according to the specific business ), so the operation here must be able to obtain the specific database. After adding this annotation, MyCat will automatically send database operations to the specified database for execution when it is executed. In this way, a simple multi-tenancy method is realized.

 

http://blog.csdn.net/isea533/article/details/56282316

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326529964&siteId=291194637