Java代码实现不同应用系统中数据同步程序

系统A---->系统B。系统A表数据有新增、修改、删除时,会把这些发生记录的数据同步至系统B。

实现思想:(一)、首先怎么确定系统A需要同步的表中数据发生了变化。

(二)、什么时候需要同步这些有变化的数据。

(三)、咋实现?

第一步:使用SQL中的触发器记录数据变化

触发器的作用是针对需要同步的表进行一个监控作用,当表数据发生了变化,触发器会立马检测到,进行数据记录,此时,我这里使用一个中间临时表进行记录。

 实现触发器的SQL:创建一个触发器名称为BIUDFER_YWCL_CASE_220905,需要针对哪张表进行检测———CCS_CASE_BASE_T。监控这张表的动作是update、insert、delete。

数字1表示新增,2表示修改,3表示删除。主要是根据针对监控的表的主键进行记录,此表的主键是caseid。

CREATE OR REPLACE TRIGGER BIUDFER_YWCL_CASE_220905
after update or insert or delete on CCS_CASE_BASE_T
FOR EACH ROW
declare
v_num number;
BEGIN
 CASE
     WHEN inserting  THEN
		insert into EXCH_TRIGGER values(:new.caseid ,'1','CCS_CASE_BASE_T',to_char(list_id.nextval));           
     WHEN UPDATING  THEN
     	select count(1) into v_num from EXCH_TRIGGER where INFO_CTRLID=:new.caseid and LIST_TABLE='CCS_CASE_BASE_T' and INFO_CTRLSTATE in('1','2');
     	if v_num=0 then
        	insert into EXCH_TRIGGER values(:new.caseid ,'2','CCS_CASE_BASE_T',to_char(list_id.nextval));  
        end if;
     WHEN DELETING THEN
     	select count(1) into v_num from EXCH_TRIGGER where INFO_CTRLID=:old.caseid and LIST_TABLE='CCS_CASE_BASE_T' and INFO_CTRLSTATE in('1');
     	if v_num=1 then
     		delete from EXCH_TRIGGER where INFO_CTRLID=:old.caseid and LIST_TABLE='CCS_CASE_BASE_T' and INFO_CTRLSTATE in('1');
     	else     	
	     	select count(1) into v_num from EXCH_TRIGGER where INFO_CTRLID=:old.caseid and LIST_TABLE='CCS_CASE_BASE_T' and INFO_CTRLSTATE in('2');
	     	if v_num=1 then
		     	delete from EXCH_TRIGGER where INFO_CTRLID=:old.caseid and LIST_TABLE='CCS_CASE_BASE_T' and INFO_CTRLSTATE in('2');
		        insert into EXCH_TRIGGER values(:old.caseid ,'3','CCS_CASE_BASE_T',to_char(list_id.nextval)); 
	     	else     	
	        	insert into EXCH_TRIGGER values(:old.caseid ,'3','CCS_CASE_BASE_T',to_char(list_id.nextval));  
	        end if;
     	end if;
     END CASE;
END;

临时表EXCH_TRIGGER,建表语句

CREATE TABLE "EXCH_TRIGGER"
(
"INFO_CTRLID" VARCHAR2(40),
"INFO_CTRLSTATE" VARCHAR2(1),
"LIST_TABLE" VARCHAR2(200),
"LIST_ID" VARCHAR2(18) NOT NULL,
NOT CLUSTER PRIMARY KEY("LIST_ID")) STORAGE(ON "MAIN", CLUSTERBTR) ;
COMMENT ON TABLE "EXCH_TRIGGER" IS '导库控制表';
COMMENT ON COLUMN "EXCH_TRIGGER"."INFO_CTRLSTATE" IS '操作数据库状态:1=insert,2=update,3=delete';
COMMENT ON COLUMN "EXCH_TRIGGER"."LIST_TABLE" IS '操作表';

 临时表的序列,自增id。

CREATE SEQUENCE "LIST_ID" INCREMENT BY 1 START WITH 1 MAXVALUE 999999999 MINVALUE 1 CACHE 20;

第二步、Java程序实现

代码中要随时知道表中有记录生成,就需要用到定时任务。所以就是编写定时任务。

<?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:dwr="http://www.directwebremoting.org/schema/spring-dwr"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.0.xsd 
		http://www.directwebremoting.org/schema/spring-dwr
    	http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd">
    <bean id="quartz" lazy-init='false' class="org.springframework.scheduling.quartz.SchedulerFactoryBean"></bean> 
	<!-- 用于定时同步数据 -->
	<bean id="MyDzfwQuartz" class="com.zrar.main.quartz.MyDzfwQuartz"></bean>
    	<!-- 定义调用对象和调用对象的方法 -->
    <bean id="MyDzfwTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <!-- 调用的类 -->
        <property name="targetObject">
            <ref bean="MyDzfwQuartz"/>
        </property>
        <!-- 调用类中的方法 -->
        <property name="targetMethod" value="dataChange">
        </property>
    </bean>
    <bean id="MyDzfwTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail" ref="MyDzfwTask" /> 
		<!-- 每1分钟执行一次 -->
		<property name="cronExpression" value="0 * * * * ?" />
	</bean>     
	<!-- 用于定时同步数据 -->
	<bean id="HljToGxbZskQuartz" class="com.zrar.main.quartz.HljToGxbZskQuartz"></bean>
    	<!-- 定义调用对象和调用对象的方法 -->
    <bean id="HljToGxbZskDataChangeTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <!-- 调用的类 -->
        <property name="targetObject">
            <ref bean="HljToGxbZskQuartz"/>
        </property>
        <!-- 调用类中的方法 -->
        <property name="targetMethod" value="dataChange">
        </property>
    </bean>
    <bean id="HljToGxbZskDataChangeTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail" ref="HljToGxbZskDataChangeTask" />
		<!-- 每1分钟执行一次 -->
		<property name="cronExpression" value="0 * * * * ?" />
	</bean>
	<!-- 用于定时同步数据 -->
	<bean id="HljToGxbQuartz" class="com.zrar.main.quartz.HljToGxbQuartz"></bean>
    	<!-- 定义调用对象和调用对象的方法 -->
    <bean id="HljToGxbDataChangeTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <!-- 调用的类 -->
        <property name="targetObject">
            <ref bean="HljToGxbQuartz"/>
        </property>
        <!-- 调用类中的方法 -->
        <property name="targetMethod" value="dataChange">
        </property>
    </bean>
    <bean id="HljToGxbDataChangeTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail" ref="HljToGxbDataChangeTask" />
		<!-- 每1分钟执行一次 -->
		<property name="cronExpression" value="0 * * * * ?" />
	</bean>
	<!-- 用于定时同步数据 -->
	<bean id="HljToGxbYYQuartz" class="com.zrar.main.quartz.HljToGxbYYQuartz"></bean>
    	<!-- 定义调用对象和调用对象的方法 -->
    <bean id="HljToGxbYYDataChangeTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <!-- 调用的类 -->
        <property name="targetObject">
            <ref bean="HljToGxbYYQuartz"/>
        </property>
        <!-- 调用类中的方法 -->
        <property name="targetMethod" value="dataChange">
        </property>
    </bean>
    <bean id="HljToGxbYYDataChangeTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail" ref="HljToGxbYYDataChangeTask" />
		<!-- 每1分钟执行一次 -->
		<property name="cronExpression" value="0 * * * * ?" />
	</bean>
	<bean id="myDzfwStartQuertz" lazy-init="true" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" >
       <property name="triggers">
        <list>
	        <ref bean="MyDzfwTrigger"/>
	        <ref bean="HljToGxbDataChangeTrigger"/>
	        <ref bean="HljToGxbZskDataChangeTrigger"/>
	        <ref bean="HljToGxbYYDataChangeTrigger"/>
        </list>
       </property>
   </bean>                                                                                                                                                                                                                                                                                                            
</beans>

定时任务完成后,就编写实现类与方法

package com.zrar.main.quartz;

import com.alibaba.fastjson.JSONObject;
import com.zrar.easyweb.core.util.PropertyManager;
import com.zrar.easyweb.persistence.core.IBaseZrarDao;
import com.zrar.main.zskbo.ZlInfoBO;
import com.zrar.main.zskbo.ZlInfoNrBO;
import com.zrar.main.util.HttpRequestUtil;
import com.zrar.main.vo.ExchCaseTriggerVO;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HljToGxbZskQuartz {

    private static String HLJTOGXBZSK_URL= PropertyManager.getProperty("HLJTOGXBZSK_URL","application");

    //黑龙江知识库的ZL_INFO、ZL_INFO_NR
    public static Map<String, Class> zsk= new HashMap<String, Class>();
    static {
        zsk.put("ZL_INFO", ZlInfoBO.class);
        zsk.put("ZL_INFO_NR", ZlInfoNrBO.class);
    }

    @Resource
    private IBaseZrarDao daozsk;

    public void dataChange() {
        String sql="select * from EXCH_TRIGGER order by to_number(LIST_ID)";
        String sql1="delete from EXCH_TRIGGER where LIST_ID=?";
        List<ExchCaseTriggerVO> ls= daozsk.getList(sql, ExchCaseTriggerVO.class);
        for(ExchCaseTriggerVO vo:ls) {
            String cid=vo.getInfoCtrlid();
            String stat=vo.getInfoCtrlstate();
            String table=vo.getListTable().toUpperCase();
            String id=vo.getListId();
            Map<String,Object> m1= new HashMap<String, Object>();
            m1.put("cid", cid);
            m1.put("stat", stat);
            m1.put("table", table);
            if("1".equals(stat)||"2".equals(stat)) {
                Object obj=daozsk.getBO(zsk.get(table), cid);
                m1.put("obj", obj);
            }
            String s= HttpRequestUtil.httpRequest(HLJTOGXBZSK_URL, m1);
            JSONObject jo= JSONObject.parseObject(s);
            String code=jo.getString("code");
            if("0".equals(code)) {
                daozsk.update(sql1,id);
            }
        }
    }
}
package com.zrar.main.util;

import java.nio.charset.StandardCharsets;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.zrar.easyweb.core.util.PropertyManager;

public class HttpRequestUtil {
	private static String url=PropertyManager.getProperty("JH_URL","application");
	/**   
     * 发起https请求并获取结果   
     *    
     * @param requestUrl 请求地址   
     * @param commoninfo 提交的数据   
     * @return    
     */    
	public static String httpRequest(String requestUrl, Object commoninfo){
		//返回的code -1 为失败
		String result = "{\"message\": \"%s\",\"code\": \"-1\"}";
		HttpClient client = HttpClients.createDefault();
		if(StringUtils.isEmpty(requestUrl)){
			requestUrl=url;
		}
		try {
			HttpPost post = new HttpPost(requestUrl);
			String materialInfo=JSON.toJSONString(commoninfo);
			post.setHeader(new BasicHeader("content-type", "text/plain;charset=utf-8"));
			//String body =materialInfo;
			post.setEntity(new StringEntity(materialInfo,StandardCharsets.UTF_8));
			//发送请求
			HttpResponse response = client.execute(post);
			//从response获取返回内容
			result= EntityUtils.toString(response.getEntity());
			System.out.println(result);
		}catch(Exception e){
			e.printStackTrace();
			result=String.format(result,"调用接口失败,异常信息:"+e.toString());
		}
		return result;
	}
}

第三步、系统A数据推送到接口方处理数据,存储到系统B中。

package com.zrar.main.blh;

import com.alibaba.fastjson.JSONObject;
import com.zrar.easyweb.persistence.core.IBaseZrarDao;
import com.zrar.easyweb.web.core.annotation.BLH;
import com.zrar.easyweb.web.core.annotation.Mapping;
import com.zrar.easyweb.web.core.event.IZrarRequest;
import com.zrar.easyweb.web.core.event.IZrarResponse;
import com.zrar.easyweb.web.core.event.impl.ZrarResponse;
import com.zrar.main.bo.YwclCaseBO;
import com.zrar.main.bo.YwclLzmxBO;
import com.zrar.main.cxbo.YyfwtjBO;
import com.zrar.main.zskbo.ZlInfoBO;
import com.zrar.main.zskbo.ZlInfoNrBO;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@BLH("HljToGxbBLH")
@Mapping("/hljToGxbBLH")
public class HljToGxbBLH {

	public static Map<String, Class> m= new HashMap<String, Class>();
	public static Map<String, Class> zsk= new HashMap<String, Class>();
	public static Map<String, Class> yyfwtj= new HashMap<String, Class>();
	static {
		m.put("CCS_CASE_TRANSFER_T", YwclLzmxBO.class);
		m.put("CCS_CASE_BASE_T", YwclCaseBO.class);
		zsk.put("ZL_INFO", ZlInfoBO.class);
		zsk.put("ZL_INFO_NR", ZlInfoNrBO.class);
		yyfwtj.put("TJ_YYFWFX", YyfwtjBO.class);
	}
	@Resource
	private IBaseZrarDao dao;
	@Resource
	private IBaseZrarDao daozsk;
	@Resource
	private IBaseZrarDao daocx;

	/**
	 * 获取传输的数据
	 * @param request
	 * @return
	 */
	private String getQueryString(HttpServletRequest request){
		StringBuffer sb = new StringBuffer();
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		try{
			is = request.getInputStream();
			isr = new InputStreamReader(is, "UTF-8");
			br = new BufferedReader(isr);
			String ss = "";
			while ((ss = br.readLine()) != null) {
				sb.append(ss);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(br != null){
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(isr != null){
				try {
					isr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}

	/**
	 * @Description:黑龙江工信部数据同步至部里(主表和流转明细表)
	 * CCS_CASE_TRANSFER_T  CCS_CASE_BASE_T
	 * @Author: simajilai
	 * @date: 2022/9/5 17:13
	 **/
	@Mapping("/hljToGxbDataChange")
	public IZrarResponse hljToGxbDataChange(IZrarRequest req) {
		IZrarResponse res = new ZrarResponse();
		HttpServletRequest request=req.getHttpServletRequest();
		//获取参数流
		String queryString=getQueryString(request);
//		System.out.println(queryString);
		JSONObject jo= JSONObject.parseObject(queryString);
		String table=jo.getString("table");
		String stat=jo.getString("stat");
		String cid=jo.getString("cid");
		Class c=m.get(table);
		if("3".equals(stat)) {
			Object o=dao.getBO(c, cid);
			if(o!=null) {
				dao.deleteBO(o);
			}
		}else if("1".equals(stat)||"2".equals(stat)) {
			JSONObject jo1= jo.getJSONObject("obj");
			Object o=JSONObject.parseObject(jo1.toString(), c);
			dao.saveOrUpdateBO(Arrays.asList(o));
		}
		res.addResHtml("{\"code\":\"0\",\"message\":\"数据交互成功\"}");
		return res;
	}
	/**
	 * @Description:
	 * @Author: simajilai
	 * @date: 2022/9/6 8:41
	 **/
	@Mapping("/hljToGxbZskDataChange")
	public IZrarResponse hljToGxbZskDataChange(IZrarRequest req) {
		IZrarResponse res = new ZrarResponse();
		HttpServletRequest request=req.getHttpServletRequest();
		//获取参数流
		String queryString=getQueryString(request);
//		System.out.println(queryString);
		JSONObject jo= JSONObject.parseObject(queryString);
		String table=jo.getString("table");
		String stat=jo.getString("stat");
		String cid=jo.getString("cid");
		Class c=zsk.get(table);
		if("3".equals(stat)) {
			Object o=daozsk.getBO(c, cid);
			if(o!=null) {
				daozsk.deleteBO(o);
			}
		}else if("1".equals(stat)||"2".equals(stat)) {
			JSONObject jo1= jo.getJSONObject("obj");
			Object o=JSONObject.parseObject(jo1.toString(), c);
			daozsk.saveOrUpdateBO(Arrays.asList(o));
		}
		res.addResHtml("{\"code\":\"0\",\"message\":\"数据交互成功\"}");
		return res;
	}

	/**
	 * @Description:语音服务统计
	 * @Author: simajilai
	 * @date: 2022/9/6 16:06
	 **/
	@Mapping("/hljToGxbYYDataChange")
	public IZrarResponse hljToGxbYYDataChange(IZrarRequest req) {
		IZrarResponse res = new ZrarResponse();
		HttpServletRequest request=req.getHttpServletRequest();
		//获取参数流
		String queryString=getQueryString(request);
//		System.out.println(queryString);
		JSONObject jo= JSONObject.parseObject(queryString);
		String table=jo.getString("table");
		String stat=jo.getString("stat");
		String cid=jo.getString("cid");
		Class c=yyfwtj.get(table);
		if("3".equals(stat)) {
			Object o=daocx.getBO(c, cid);
			if(o!=null) {
				daocx.deleteBO(o);
			}
		}else if("1".equals(stat)||"2".equals(stat)) {
			JSONObject jo1= jo.getJSONObject("obj");
			Object o=JSONObject.parseObject(jo1.toString(), c);
			daocx.saveOrUpdateBO(Arrays.asList(o));
		}
		res.addResHtml("{\"code\":\"0\",\"message\":\"数据交互成功\"}");
		return res;
	}
}

第四步、如果数据同步涉及到不同的库,什么应用库、查询库、知识库之类的,那么就需要配置数据源。。。

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

	<!-- 定义受环境影响易变的变量 载入属性文件 -->
	<context:property-placeholder location="classpath*:*.properties" />
	 
	<!--  Oracle/SqlServer -->
	<bean id="dataSourceTargetcx" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
		<property name="driverClassName" value="${cx.hibernate.connection.driver_class}"></property>
		<property name="url" value="${cx.hibernate.connection.url}" />
		<property name="username"><value>${cx.hibernate.connection.username}</value></property>
		<property name="password" value="${cx.hibernate.connection.password}"/>
	     <property name="filters"><value>stat</value></property>
	     <property name="maxActive"><value>50</value></property>
	     <property name="initialSize"><value>1</value></property>
	     <property name="maxWait"><value>60000</value></property>
	     <property name="minIdle"><value>1</value></property>
	     <property name="timeBetweenEvictionRunsMillis"><value>60000</value></property>
	     <property name="minEvictableIdleTimeMillis"><value>300000</value></property>
	     <property name="validationQuery"><value>SELECT 'x' from dual</value></property>
	     <property name="testWhileIdle"><value>true</value></property>
	     <property name="testOnBorrow"><value>false</value></property>
	     <property name="testOnReturn"><value>false</value></property>
	     <property name="poolPreparedStatements"><value>true</value></property>
	     <property name="maxOpenPreparedStatements"><value>20</value></property>
	 </bean>

	<!-- 数据源配置 -->
	<bean id="sessionFactorycx"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSourceTargetcx" />
		<!-- <property name="namingStrategy">
			<bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
		</property> -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.format_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.generate_statistics">false</prop>
			</props>
		</property>
		<property name="packagesToScan">
			<list>
			<value>com.zrar.main.cxbo</value>
			</list>
		</property>
	</bean>
	
	<!-- 默认数据源对象 -->
	<bean id="persistemce_oraclecx" class="org.springframework.orm.hibernate4.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactorycx"></property>
	</bean>
	<bean id="persistemce_oracle_jdbccx" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSourceTargetcx"></property>
	</bean>



	<!-- Mybatis DataSource Configuration -->
	<bean id="sqlSessionFactorycx" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSourceTargetcx" />
		<property name="configLocation" value="classpath:mybatis-config.xml" />  
		<property name="mapperLocations" value="classpath*:mappers/**/*.xml"></property>
	</bean>
	
	<bean id="sqlSessioncx" class="org.mybatis.spring.SqlSessionTemplate">
	  <constructor-arg index="0" ref="sqlSessionFactorycx" />
	</bean>
	
	<!-- 数据库操作接口 -->
	<bean id="daocx" class="com.zrar.easyweb.persistence.core.factory.BaseZrarDaoFactory">
		<property name="hbTemplate" ref="persistemce_oraclecx" />
		<property name="jdbcTemplate" ref="persistemce_oracle_jdbccx" />
		<property name="sqlSession" ref="sqlSessioncx"></property>
	</bean>
	


</beans>

 配置多个数据源的文件application.properties。

# [\u6570\u636E\u5E93\u914D\u7F6E]
#hibernate.connection.driver_class=oracle.jdbc.driver.OracleDriver
#hibernate.connection.url=jdbc:oracle:thin:@192.168.2.242:1521:ora242
#hibernate.connection.username=gxb12381
#hibernate.connection.password=gxb12381
hibernate.connection.driver_class=dm.jdbc.driver.DmDriver
hibernate.connection.url=jdbc:dm://192.168.2.240:5236
hibernate.connection.username=hlj12381
hibernate.connection.password=arkj123456
hibernate.dialect=org.hibernate.dialect.OracleDialect
hibernate.default_schema=gxb
hibernate.show_sql=false
hibernate.format_sql=true

cx.hibernate.connection.driver_class=dm.jdbc.driver.DmDriver
cx.hibernate.connection.url=jdbc:dm://192.168.2.240:5236
cx.hibernate.connection.username=hlj12381cx
cx.hibernate.connection.password=arkj123456

zsk.hibernate.connection.driver_class=dm.jdbc.driver.DmDriver
zsk.hibernate.connection.url=jdbc:dm://192.168.2.240:5236
zsk.hibernate.connection.username=hljzsk
zsk.hibernate.connection.password=arkj123456

# Redis settings    
# server IP  
redis.host=192.168.8.1
# server port  
redis.port=6379
# use dbIndex  
redis.database=0
redis.password=

# \u63a7\u5236\u4e00\u4e2apool\u6700\u591a\u6709\u591a\u5c11\u4e2a\u72b6\u6001\u4e3aidle(\u7a7a\u95f2\u7684)\u7684jedis\u5b9e\u4f8b  
redis.maxIdle=300
# \u8868\u793a\u5f53borrow(\u5f15\u5165)\u4e00\u4e2ajedis\u5b9e\u4f8b\u65f6\uff0c\u6700\u5927\u7684\u7b49\u5f85\u65f6\u95f4\uff0c\u5982\u679c\u8d85\u8fc7\u7b49\u5f85\u65f6\u95f4(\u6beb\u79d2)\uff0c\u5219\u76f4\u63a5\u629b\u51faJedisConnectionException\uff1b  
redis.maxWait=3000
# \u5728borrow\u4e00\u4e2ajedis\u5b9e\u4f8b\u65f6\uff0c\u662f\u5426\u63d0\u524d\u8fdb\u884cvalidate\u64cd\u4f5c\uff1b\u5982\u679c\u4e3atrue\uff0c\u5219\u5f97\u5230\u7684jedis\u5b9e\u4f8b\u5747\u662f\u53ef\u7528\u7684  
redis.testOnBorrow=true
# \u6700\u5927\u8fde\u63a5\u6570
redis.maxActive=300

JH_URL=http://127.0.0.1:8800/api/dataChange
HLJTOGXB_URL=http://127.0.0.1:8800/hljToGxbBLH/hljToGxbDataChange
HLJTOGXBZSK_URL=http://127.0.0.1:8800/hljToGxbBLH/hljToGxbZskDataChange
HLJTOGXBYY_URL=http://127.0.0.1:8800/hljToGxbBLH/hljToGxbYYDataChange

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在 Java ,可以使用 JDBC (Java Database Connectivity) 来连接到数据库并执行同步操作。 下面是一个简单的示例,假设你已经有了连接到数据库代码: ``` String sql = "INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)"; PreparedStatement statement = connection.prepareStatement(sql); // 设置要插入的值 statement.setString(1, "value1"); statement.setString(2, "value2"); statement.setString(3, "value3"); // 执行插入 statement.executeUpdate(); ``` 这段代码会向数据库的表插入一条新记录。你也可以使用其他的 SQL 语句,例如 UPDATE 或 DELETE,来执行其他类型的同步操作。 希望这个示例能帮到你。 ### 回答2: Java数据库同步代码是用于在不同数据库进行数据同步程序代码。在实际应用,经常需要将一个数据库数据同步到另一个数据库,以保持数据的一致性和及时性。 首先,我们需要建立源数据库和目标数据库的连接。通常情况下,我们使用JDBC来连接数据库。在代码,我们需要指定源数据库和目标数据库的相关信息,如数据库驱动、数据库URL、用户名和密码等。 接下来,我们需要执行数据库查询语句,获取源数据库数据。通过执行查询语句,我们可以获取到需要同步数据。 然后,我们需要将源数据库数据插入到目标数据库。我们可以使用SQL语句或者ORM框架来完成数据插入操作。在插入数据时,需要注意目标数据库是否已经存在相同的数据,如果存在,可能需要进行更新操作。 在数据插入完成后,我们可以进行一些后续操作。例如,可以记录同步日志,方便后续进行数据追踪和排查问题。还可以发送通知,如邮件或短信,通知相关人员数据同步已完成。 最后,我们需要关闭数据库连接,释放资源。通过调用相应的API,我们可以关闭数据库连接,确保不占用过多的系统资源。 需要特别注意的是,Java数据库同步代码在处理大数据量的情况下,可能会面临性能的挑战。在编写代码时,可以考虑使用分批同步的方式,将大的数据集分成多个小批次进行同步,以提高效率。 总之,Java数据库同步代码是一种将源数据库数据同步到目标数据库程序代码。通过建立数据库连接、执行查询语句、数据插入和后续操作,我们可以完成数据同步的过程,并保持数据的一致性和及时性。 ### 回答3: 在Java,可以使用JDBC(Java Database Connectivity)来实现数据库同步操作。以下是一个简单的示例代码,展示了如何使用Java同步两个数据库数据。 首先,我们需要导入相应的JDBC库,例如MySQL的JDBC驱动程序。然后,我们需要建立两个数据库的连接,一个是源数据库,另一个是目标数据库。 ```java import java.sql.*; public class DatabaseSync { public static void main(String[] args) { Connection sourceConn = null; Connection targetConn = null; try { // 创建源数据库连接 sourceConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/source_db", "username", "password"); // 创建目标数据库连接 targetConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/target_db", "username", "password"); // 创建源数据库的查询语句 Statement sourceStmt = sourceConn.createStatement(); ResultSet sourceRs = sourceStmt.executeQuery("SELECT * FROM table_name"); // 创建目标数据库的更新语句 PreparedStatement targetStmt = targetConn.prepareStatement("INSERT INTO table_name VALUES (?, ?)"); // 迭代源数据库的结果集 while (sourceRs.next()) { // 获取源数据库数据 int column1 = sourceRs.getInt("column1"); String column2 = sourceRs.getString("column2"); // 设置目标数据库更新语句的参数 targetStmt.setInt(1, column1); targetStmt.setString(2, column2); // 执行目标数据库的更新语句 targetStmt.executeUpdate(); } // 关闭连接和声明 sourceRs.close(); sourceStmt.close(); targetStmt.close(); sourceConn.close(); targetConn.close(); System.out.println("数据库同步完成!"); } catch (SQLException e) { e.printStackTrace(); } } } ``` 上述代码,我们首先创建源数据库的查询语句,然后创建目标数据库的更新语句。在迭代源数据库的结果集时,我们从源数据库获取数据,并将其设置为目标数据库更新语句的参数。最后,执行目标数据库的更新语句,将数据插入到目标数据库。 需要注意的是,上述代码只是一个简单的示例,实际的同步过程可能需要更复杂的逻辑和额外的步骤,例如数据转换、更新冲突解决等。因此,在实际的开发过程,可能需要根据具体的需求进行更多的调整和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值