SSH实现动态数据源切换

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
简介:

目录:

SSH的整合:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>dynamicDBsource</display-name>
  <welcome-file-list>
 
    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>
 
  
  
    <filter>
	    <filter-name>struts2</filter-name>
	    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  	</filter>
 	<filter-mapping>
	    <filter-name>struts2</filter-name>
	    <url-pattern>/*</url-pattern>
  	</filter-mapping>
  
  
  
   
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext*.xml</param-value>
  </context-param>
  
</web-app>

struts.xml



<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="true" />

    <package name="default" namespace="/" extends="struts-default">
    
       <action name="student_*" class="com.xh.dataSource.action.StuAction" method="{1}">
       		<result name="addUI">/WEB-INF/view/addUI.jsp</result>
   			<result name="list">/WEB-INF/view/list.jsp</result>
   			<result name="add">/WEB-INF/view/list.jsp</result>
   			<result name="#">index.jsp</result>
       		
   
       </action>
       
      
    </package>

</struts>


applicatonContext.xml

<?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:context="http://www.springframework.org/schema/context"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<!--自动扫描和装配 -->
	<context:component-scan base-package="com.xh.dataSource"></context:component-scan>
	
	<!-- 导入外部的properties文件 -->
	<context:property-placeholder location="classpath:jdbc.properties"/>
	
	
	<!-- 配置sessionFactory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
	
		<!-- 指定hibernate的配置文件位置 -->
		<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
		<!-- c3p0数据库连接信息 -->
		<property name="dataSource" ref="MYdataSource"></property>
			

	</bean>
	
	
	
	<bean id="MYdataSource" class="com.xh.dataSource.ds.MyDataSource">
		<property name="targetDataSources"> 
	     	<map key-type="java.lang.String">  
	        		<entry key="dataSource0" value-ref="dataSource0"/>  
	         		<entry key="dataSource1" value-ref="dataSource1"/>  
	      	</map>  
   		</property>  
  		<property name="defaultTargetDataSource" ref="dataSource1"/>  
	</bean>
	
	
	
	<bean id="dataSource0" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="jdbcUrl" value="jdbc:mysql:///db0"></property>
		<property name="driverClass" value="com.jdbc.mysql.Driver"></property>
		<property name="user" value="root"></property>
		<property name="password" value="root"></property>
				
	</bean>
	
	
	
	<bean id="dataSource1" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="jdbcUrl" value="jdbc:mysql:///db1"></property>
		<property name="driverClass" value="com.jdbc.mysql.Driver"></property>
		<property name="user" value="root"></property>
		<property name="password" value="root"></property>
				
	</bean>
	
	
	
	<!-- 配置声明式事务管理(采用注解的方式) -->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
	<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<tx:annotation-driven transaction-manager="txManager"/>
	
	</beans>


hibernate.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
    
    	<!-- 1,数据库连接信息 -->
	<property name="dialect">
		org.hibernate.dialect.MySQL5InnoDBDialect
	</property>


	<!-- 2,其他配置 -->
	<property name="show_sql">true</property>
	<property name="hbm2ddl.auto">update</property>

	<!-- 3,导入映射文件 -->
	<mapping resource="com/xh/dataSource/entity/Student.hbm.xml" />
	
    	
    </session-factory>
</hibernate-configuration>



action

package com.xh.dataSource.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;


import org.apache.struts2.interceptor.RequestAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.xh.dataSource.ds.DataSourceContextHolder;
import com.xh.dataSource.ds.MyDataSource;
import com.xh.dataSource.entity.Student;
import com.xh.dataSource.service.StuService;


public class StuAction extends ActionSupport implements ModelDriven<Student> ,RequestAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Resource
	StuService stuService;

	
	Map<String, Object> request=new HashMap<>();
	
	List<Student> stus;
	public List<Student> getStus() {
		return stus;
	}



	public void setStus(List<Student> stus) {
		this.stus = stus;
	}




	@Resource
	Student stu;

	public String list()
	{
		stus=stuService.lsit();
		System.out.println("stus:>>"+stus.size());
		ActionContext.getContext().put("stusList", stus);
		return "list";
	}
	
	
	
	public String add()
	{	
		System.out.println("ID>>>"+stu.getId()+"NAME>>>"+stu.getName());
		stuService.add(stu);
		return "add";
	}
	
	
	
	
	public String addUI()
	{
		return "addUI";
	}


	
	
	
	public String dataSource0() {
		DataSourceContextHolder.setDataSourceType("dataSource0");
		return "#";
	}

	public String dataSource1() {
		DataSourceContextHolder.setDataSourceType("dataSource1");
		return "#";
	}
	

	@Override
	public Student getModel() {
		// TODO Auto-generated method stub
		stu=new Student();
		return stu;
	}



	@Override
	public void setRequest(Map<String, Object> arg0) {
		// TODO Auto-generated method stub
		request=arg0;
	}
	
	
	
	
}


service

package com.xh.dataSource.service;


import java.util.List;


import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.xh.dataSource.dao.StuDao;
import com.xh.dataSource.entity.Student;
@Component
public class StuService {

	@Resource
	StuDao stuDao;
	
	public List<Student> lsit() {
		return stuDao.list();
		
	}
	
	
	
	public void add(Student stu) {
		System.out.println("service---ID>>>"+stu.getId()+"NAME>>>"+stu.getName());
		stuDao.add(stu);
		
	}
}




dao

package com.xh.dataSource.dao;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.xh.dataSource.entity.Student;
@Component
public class StuDao {
	@Resource
	SessionFactory sessionFactory;
	
	
	@SuppressWarnings("unchecked")
	public List<Student> list() {
		List<Student> stus=new ArrayList<>();
		stus=sessionFactory.openSession().createQuery("FROM Student").list();
		return stus;
		
	}
	
	
	@Transactional
	public void add(Student stu) {
		System.out.println("dao----ID>>>"+stu.getId()+"NAME>>>"+stu.getName());
		sessionFactory.openSession().save(stu);
		
	}
}



entity

package com.xh.dataSource.entity;

import org.springframework.stereotype.Component;

@Component
public class Student {

	private Long id;
	private String name;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
}



*.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-2-3 9:36:30 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.xh.dataSource.entity.Student" table="STUDENT">
        <id name="id" >
            <column name="ID" default="1" />
            <generator class="native"  />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
    </class>
</hibernate-mapping>




数据源切换相关

ds:

package com.xh.dataSource.ds;

public class DataSourceContextHolder {
	
	@SuppressWarnings("rawtypes")
	private static final ThreadLocal contextHolder=new ThreadLocal();  
    
    @SuppressWarnings("unchecked")
	public static void setDataSourceType(String dataSourceName){  
        contextHolder.set(dataSourceName);  
    }  
       
    public static String getDataSourceName(){  
        return (String) contextHolder.get();  
    }  
       
    public static void clearDataSourceType(){  
        contextHolder.remove();  
    }  
    
    
    
    
}


package com.xh.dataSource.ds;

import java.sql.SQLFeatureNotSupportedException;
import java.util.Map;
import java.util.logging.Logger;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.jdbc.datasource.lookup.DataSourceLookup;
import org.springframework.stereotype.Component;



public class MyDataSource extends AbstractRoutingDataSource{


	private Map<String,String> myds;


	public Map<String,String> getMyds() {
		return myds;
	}

	public void setMyds(Map<String,String> myds) {
		this.myds = myds;
	}

	 @Override  
	    public Object determineCurrentLookupKey() {  
	        return DataSourceContextHolder.getDataSourceName();  
	    }  
	   
	    @Override  
	    public void setDataSourceLookup(DataSourceLookup dataSourceLookup) {  
	        super.setDataSourceLookup(dataSourceLookup);  
	    }  
	   
	    @Override  
	    public void setDefaultTargetDataSource(Object defaultTargetDataSource) {  
	        super.setDefaultTargetDataSource(defaultTargetDataSource);  
	    }  
	   
	    @Override  
	    public void setTargetDataSources(Map targetDataSources) {  
	        super.setTargetDataSources(targetDataSources);  
	        //重点  
	        super.afterPropertiesSet();  
	    }

		@Override
		public Logger getParentLogger() throws SQLFeatureNotSupportedException {
			// TODO Auto-generated method stub
			return null;
		}  
	
}


前台页面:

index.jap

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="student_addUI">ADDstudents</a>
<br>
<br>
<a href="student_list">LISTstudents</a>
<br>
<br>
<a href="student_dataSource0">dataSource0</a>
<br>
<br>
<a href="student_dataSource1">dataSource1</a>
</body>
</html>

list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <%@ taglib prefix="s" uri="/struts-tags" %>         
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<s:iterator value="#stusList">
<tr>
<td>${id}</td>
<td>${name}</td>
<br>

</tr>
		

</s:iterator>

</body>
</html>

addUI.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<s:form action="student_add" method="post">
	<s:textfield name="id" label="学生ID"></s:textfield>
	<s:textfield name="name" label="学生姓名"></s:textfield>
	<input type="submit" value="提  交"/s>
</s:form>

</body>
</html>




相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
网络安全 开发框架 开发工具
intellij idea搭建ssh开发框架之绑定数据源
原文: intellij idea搭建ssh开发框架之绑定数据源 在intellij idea中绑定数据源并生成hibernate实体对象。
1695 0
|
关系型数据库 Java 数据库连接
SSH框架系列:Spring配置多个数据源
  分类: 【java】2013-12-09 16:59 1247人阅读 评论(0) 收藏 举报 1.问题的引入          对于普通的SSH框架而言,一般配置一个数据源,一个SessionFactory,一个事务管理和对应的ProxyCreate。
796 0
|
14天前
|
监控 Ubuntu Linux
使用VSCode通过SSH远程登录阿里云Linux服务器异常崩溃
通过 VSCode 的 Remote - SSH 插件远程连接阿里云 Ubuntu 22 服务器时,会因高 CPU 使用率导致连接断开。经排查发现,VSCode 连接根目录 ".." 时会频繁调用"rg"(ripgrep)进行文件搜索,导致 CPU 负载过高。解决方法是将连接目录改为"root"(或其他具体的路径),避免不必要的文件检索,从而恢复正常连接。
|
5月前
|
安全 Linux Shell
Linux中SSH命令介绍
Linux中SSH命令介绍
136 2
|
3月前
|
安全 Linux 网络安全
在Linux中,如何配置SSH以确保远程连接的安全?
在Linux中,如何配置SSH以确保远程连接的安全?
|
3月前
|
安全 Linux Shell
SSH 命令完整实用指南 | Linux SSH 服务
【8月更文挑战第20天】
416 0
|
3月前
|
安全 Linux Shell
如何在 Linux 服务器上配置基于 SSH 密钥的身份验证
如何在 Linux 服务器上配置基于 SSH 密钥的身份验证
188 0
|
3月前
|
Linux 网络安全 数据安全/隐私保护
Linux——配置SSH免密登录
Linux——配置SSH免密登录
96 0
|
4月前
|
安全 Ubuntu Linux
记录一次Linux服务器被人使用SSH字典爆破
曾经我以为互联网到至今应该是很和平的状态,但是经历了这次ssh字典爆破攻击后我才意识到网络攻击无处不在,建议系统密码使用比较复杂的随机字符组合,七八十位都没问题,数据可贵,电脑该装杀毒软件的就装上,别因为那占用那点内存而舍弃杀毒软件,防网络攻击于未然 !
|
5月前
|
Shell Linux 网络安全
Linux怎样在使用ssh 链接时就指定gcc 的版本
Linux怎样在使用ssh 链接时就指定gcc 的版本
60 7