工具类:
1.DBContextHolder
package web.Bean;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DBContextHolder extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
// 从自定义的位置获取数据源标识
return DynamicDataSourceHolder.getDataSource();
}
}
2.DynamicDataSource
package web.Bean;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
protected Object determineCurrentLookupKey() {
return DynamicDataSourceHolder.getDataSource();
}
}
3.DynamicDataSourceHolder
package web.Bean;
public class DynamicDataSourceHolder {
private static final ThreadLocal<String> THREAD_DATA_SOURCE = new ThreadLocal();
public static String getDataSource() {
return (String) THREAD_DATA_SOURCE.get();
}
public static void setDataSource(String dataSource) {
THREAD_DATA_SOURCE.set(dataSource);
}
public static void clearDataSource() {
THREAD_DATA_SOURCE.remove();
}
}
controller
package web.controller;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import web.Bean.DBContextHolder;
import web.Bean.DynamicDataSourceHolder;
import web.mapping.student;
import web.service.InterfaceDataListService;
import web.service.SecondService;
import web.serviceImpl.RedisService;
import com.alibaba.fastjson.JSONObject;
@Controller
public class BuwanzhengshuController {
@Autowired
private InterfaceDataListService interfaceDataListService;
@Autowired
private SecondService secondService;
/**
* 同时查询两个数据库的数据
*
*/
@RequestMapping(value = "demo04", method = RequestMethod.GET, produces =