In the Spring environment, MyBatis supports multiple Datasource Reference implementations.

Source: Internet
Author: User

In the Spring environment, MyBatis supports multiple Datasource Reference implementations.
Background

Recently, an old system needs to be transformed for a project. The old system uses Oracle as the storage, implements business code with massive PL/SQL code, and Socket Server with C as the bridge between Client and PL/SQL. As expected, the biggest problem with the old system is the huge PL/SQL code volume (several tens of thousands of Procedure), which is unorganized and cannot be changed, followed by performance problems. The change direction is to kick out PL/SQL from Oracle and use Java to rewrite the relevant business logic and put it in the Web Server. However, the Schema in Oracle does not change.

At this point, the transformation of the old system has nothing to do with the theme I want to share. The problem arises,The old system has three sets: A, B, and C. That is to say, there are three Oracle databases, with the same Schema and PL/SQL.But the data has nothing to do with, completely independent of the three databases. It is hard to judge the historical problems, but it is only to solve the performance problem. Three sets are implemented, and the customer is allocated to different sets of systems. It is a different idea to start a server with a traditional game.

We have three solutions:
1. Deploy three sets of webservers. For the three Oracle databases, the client is connected to different Web servers, which is the same as the original architecture. Both the database and Server continue to score points.
2. Integrate the three databases into one database and deploy a set of Web servers. Data and, Server and.
3. Keep the three Oracle databases unchanged. One Web Server, but the Server needs to manage all three Oracle databases.

Solution 1 is the simplest and easiest, but when the performance is no longer a problem, we need to deploy three sets of Web servers. It is a bit difficult to say, and the O & M work has increased, the client maintains different versions (server addresses) and is reluctant to choose.

Solution 2 is difficult and difficult. The original three Oracle databases are completely independent and have no global primary keys. Basically, data cannot be partitioned. Give up!

Solution 3 is a one-off solution, and the Chinese people pay attention to the "moderate" approach. Finally, we chose solution 3.

Design Concept

Solution 3 solves the problem of how the same Server integrates three databases, specifically how to manage the three Datasouce with identical Shema in Spring. The technical selection of our system Server is the common Spring + MyBatis. Manage different Datasouce of multiple Shema instances. There are many examples on the Internet. Is Schema the same? Is it called database sharding? Is it very rare? In the Spring environment? Not found. Emphasize that Spring only needs to know one Mapper, not three. Because Spring only wants to know one Er er, not three.

The key technical difficulties are as follows:

How to identify which Oracle database should the data be stored?
Our solution is to judge based on the user's locationThe user operates database B in database A for subsequent operations on Database. When you log on to the system, first check the database where the user exists. We believe that the user name and password should be unique across three databases.. How can I switch databases dynamically?
Proxy, which is implemented by proxy. A proxy is registered in the Spring container.When the proxy is called, we intercept the call. The call is dynamically switched Based on the Environment obtained during logon (which database) and delegated to MyBatis Mapper for execution.

I drew the switch. I drew only two sets of A and B, which are A, B, and C.

Instance code identifies which database should be stored

Modify Shiro's access to user information to add environment attributes. Note: the first is to traverse the data source and test the database where the user is located. Instead, use the bean name of SqlSessionFactory as the Environment name, which is simple and straightforward!

The Shiro Realm code is as follows:

public class ShiroRealm extends AuthorizingRealm {    @Autowired    private UserService userService;    @Autowired    private SecureService secureService;    @Autowired    private AuthorizationService authorizationService;    @PostConstruct    public void initAlgorithms() {        AllowAllCredentialsMatcher credentialsMatcher = new AllowAllCredentialsMatcher();        setCredentialsMatcher(credentialsMatcher);    }    @Override    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {        UsernamePasswordToken pairToken = (UsernamePasswordToken) token;        String userName = pairToken.getUsername();        String password = new String(pairToken.getPassword());        // determine env        Map
  
    envMappers = EnvMapperFactoryBean.getAllMappers(UserMapper.class);        for (String env : envMappers.keySet()) {            User user = validUser((UserMapper) envMappers.get(env), userName, password);            if (user != null) {                ShiroUser shiroUser = new ShiroUser(user.getId(), userName, user.getBranchId(), env);                String salt = user.getSalt();                byte[] saltBytes = Hex.decode(salt);                return new SimpleAuthenticationInfo(shiroUser, user.getPassword(), ByteSource.Util.bytes(saltBytes),                        getName());            }        }        return null;    }    private User validUser(UserMapper userMapper, String userName, String password) {        UserExample example = new UserExample();        example.createCriteria().andNameEqualTo(userName);        List
   
     users = userMapper.selectByExample(example);        if (users.isEmpty()) {            return null;        }        User user = users.get(0);        String salt = user.getSalt();        String tempEncoded = secureService.hash(password, salt);        if (user.getPassword().equals(tempEncoded)) {            return user;        } else {            return null;        }    }    @Override    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {        ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();        User user = userService.queryUserByName(shiroUser.getName());        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();        List
    
      roles = authorizationService.queryRoleByUserId(user.getId());        if (roles.size() > 0) {            List
     
       roleNames = ObjectProcessor.getFieldList(roles,                    new ObjectProcessor.FieldValueGetter
      
       () { @Override public String getValue(Role role) { return role.getName(); } }); info.addRoles(roleNames); List
       
         roleIds = ObjectProcessor.getFieldList(roles, new ObjectProcessor.FieldValueGetter
        
         () { @Override public Integer getValue(Role role) { return role.getId(); } }); List
         
           privileges = authorizationService.queryPrivilegeByRoleId(roleIds); if (privileges.size() > 0) { List
          
            privilegeKeys = ObjectProcessor.getFieldList(privileges, new ObjectProcessor.FieldValueGetter
           
            () { @Override public String getValue(Privilege item) { return item.getCategory() + ":" + item.getCode(); } }); info.addStringPermissions(privilegeKeys); } } return info; } public static class ShiroUser implements Serializable, Principal { private static final long serialVersionUID = 3316911162161110480L; private Integer id; private String name; private Integer branchId; private String env; public ShiroUser(Integer id, String name, Integer branchId, String env) { this.id = id; this.name = name; this.branchId = branchId; this.env = env; } public Integer getId() { return id; } public String getName() { return name; } public Integer getBranchId() { return branchId; } public String getEnv() { return env; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ShiroUser other = (ShiroUser) obj; if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public String toString() { return name; } }}
           
          
         
        
       
      
     
    
   
  
Register Spring Mapper Proxy and dynamically switch data sources

Shiro is used to obtain user information anywhere. The essence behind it is a ThreadLocal variable. Note that there will be many helpers behind the Proxy-the real Mybatis er, which must be installed at startup.

The Code is as follows:
Public class EnvMapperFactoryBean implements FactoryBean, ApplicationContextAware {
Private static final Logger log = LoggerFactory. getLogger (EnvMapperFactoryBean. class );

Private Class
  
   
    
     
      
       
        
         
          
           
            
              MapperInterface; private ApplicationContext context; private static Map
             
               > EnvMappers = new ConcurrentHashMap <> ();/*** Sets the mapper interface of the MyBatis mapper ** @ param mapperInterface * class of the interface */public void setMapperInterface (Class
              
                MapperInterface) {this. mapperInterface = mapperInterface;}/*** {@ inheritDoc} */@ SuppressWarnings ("unchecked") public T getObject () throws Exception {installEnv (); return (T) Proxy. newProxyInstance (EnvMapperFactoryBean. class. getClassLoader (), new Class [] {mapperInterface}, new MapperProxy ();} public Class
               
                 GetObjectType () {return this. mapperInterface;} public boolean isSingleton () {return true;} private static Object getRealMapper (String env, Class mapperClazz) {Map
                
                  Mappers = envMappers. get (env); if (mappers. isEmpty () {return null;} return mappers. get (mapperClazz. getName ();} public static Map
                 
                   GetAllMappers (Class mapperClazz) {Map
                  
                    Result = new HashMap <> (); String clazzName = mapperClazz. getName (); for (String env: envMappers. keySet () {Map
                   
                     Mappers = envMappers. get (env); if (mappers. containsKey (clazzName) {result. put (env, mappers. get (clazzName) ;}} return result ;}@ SuppressWarnings ("resource") private void installEnv () {String [] sqlSessionFactoryNames = context. getBeanNamesForType (SqlSessionFactory. class); if (sqlSessionFactoryNames = null | sqlSessionFactoryNames. length = 0) {throw new RuntimeException ("SqlSessionFactory not found ");} For (String env: sqlSessionFactoryNames) {SqlSessionFactory sqlSessionFactory = context. getBean (env, SqlSessionFactory. class); SqlSession sqlSession = new SqlSessionTemplate (sqlSessionFactory); T mapper = sqlSession. getMapper (mapperInterface); if (! EnvMappers. containsKey (env) {envMappers. put (env, new ConcurrentHashMap <> ();} envMappers. get (env ). put (mapperInterface. getName (), mapper) ;}@ Override public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {context = applicationContext;} private class MapperProxy implements InvocationHandler {public Object invoke (Object proxy, method method, Object [] args) throws Throwable {Object object = null; try {ShiroUser shiroUser = (ShiroUser) SecurityUtils. getSubject (). getPrincipal (); if (shiroUser = null) {throw new RuntimeException ("the user has not logged on and cannot confirm the environment");} String env = shiroUser. getEnv (); Object mapper = getRealMapper (env, method. getDeclaringClass (); if (mapper = null) {throw new RuntimeException ("mapper not found");} object = method. invoke (mapper, args);} catch (Exception e) {log. error (e. getMessage (), e); throw e;} return object ;}}}
                   
                  
                 
                
               
              
             
            
           
          
         
        
       
      
     
    
   
  
Spring configuration file

Spring configures multiple Datasource, multiple SqlSessionFactory, and one worker.


  
   
    
     
      
       
        
         
          
           
            
             
              
               
                
                 
                  
                   
                     
                      
                      
                      
                      
                      
                      
                      
                      
                      
                     
                    
                   
                  
                 
                
               
              
             
            
           
          
         
        
       
      
     
    
   
  
  
   
    
     
      
       
        
         
          
           
            
             
              
               
                
                 
                  
                   
                     
                      
                      
                     
                    
                   
                  
                 
                
               
              
             
            
           
          
         
        
       
      
     
    
   
  
  
   
    
     
      
       
        
         
          
           
            
             
              
               
                
                 
                  
                   
                     
                      
                      
                      
                      
                      
                      
                      
                      
                      
                     
                    
                   
                  
                 
                
               
              
             
            
           
          
         
        
       
      
     
    
   
  
  
   
    
     
      
       
        
         
          
           
            
             
              
               
                
                 
                  
                   
                     
                      
                      
                     
                    
                   
                  
                 
                
               
              
             
            
           
          
         
        
       
      
     
    
   
  
  
   
    
     
      
       
        
         
          
           
            
             
              
               
                
                 
                  
                   
                     
                     
                    
                   
                  
                 
                
               
              
             
            
           
          
         
        
       
      
     
    
   
  
Conclusion

This is a classic case of implementing dynamic switching during runtime through a proxy. Proxy is a very useful design mode and is worth thinking about and learning from.

Someone may ask, are there other solutions?

Some people may find it inappropriate to identify the user name and password. They can replace the user with the desired recognition algorithm, or even leave it to the client.

For dynamic switching, Spring's javasactroutingdatasource is a good choice, but it is not suitable for our scenario. We need to first obtain three Mybatis UserMapper to test which database to use, datasource is too low-level. If the environment is determined by the client, AbstractRoutingDataSource is indeed a better choice.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.