作者 hekf2021

多数据库动态切换

  1 +<?xml version="1.0" encoding="UTF-8"?>
  2 +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4 + <modelVersion>4.0.0</modelVersion>
  5 +
  6 + <groupId>com</groupId>
  7 + <artifactId>autodatasource</artifactId>
  8 + <version>1.0</version>
  9 +
  10 + <name>autodatasource</name>
  11 +
  12 + <properties>
  13 + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  14 + <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  15 + <java.version>1.8</java.version>
  16 + </properties>
  17 +
  18 + <parent>
  19 + <groupId>org.springframework.boot</groupId>
  20 + <artifactId>spring-boot-starter-parent</artifactId>
  21 + <version>1.5.6.RELEASE</version>
  22 + <relativePath/>
  23 + </parent>
  24 +
  25 + <dependencies>
  26 + <dependency>
  27 + <groupId>org.springframework.cloud</groupId>
  28 + <artifactId>spring-cloud-dependencies</artifactId>
  29 + <version>Dalston.SR2</version>
  30 + <type>pom</type>
  31 + <scope>import</scope>
  32 + </dependency>
  33 + <dependency>
  34 + <groupId>org.springframework.cloud</groupId>
  35 + <artifactId>spring-cloud-starter-eureka</artifactId>
  36 + <version>1.3.2.RELEASE</version>
  37 + </dependency>
  38 + <dependency>
  39 + <groupId>org.springframework.boot</groupId>
  40 + <artifactId>spring-boot-starter-web</artifactId>
  41 + <version>1.5.6.RELEASE</version>
  42 + </dependency>
  43 + <dependency>
  44 + <groupId>org.springframework.boot</groupId>
  45 + <artifactId>spring-boot-starter-data-jpa</artifactId>
  46 + <version>1.5.6.RELEASE</version>
  47 + </dependency>
  48 + <dependency>
  49 + <groupId>com.alibaba</groupId>
  50 + <artifactId>druid-spring-boot-starter</artifactId>
  51 + <version>1.1.2</version>
  52 + </dependency>
  53 + <dependency>
  54 + <groupId>mysql</groupId>
  55 + <artifactId>mysql-connector-java</artifactId>
  56 + <version>5.1.40</version>
  57 + </dependency>
  58 + <dependency>
  59 + <groupId>junit</groupId>
  60 + <artifactId>junit</artifactId>
  61 + <version>4.11</version>
  62 + <scope>test</scope>
  63 + </dependency>
  64 +
  65 + </dependencies>
  66 +
  67 +</project>
  1 +CREATE TABLE aberrant
  2 +(
  3 + aberrant_id INT NOT NULL AUTO_INCREMENT,
  4 + order_no INT,
  5 + reason VARCHAR(64),
  6 + created TIMESTAMP DEFAULT CURRENT_TIMESTAMP NULL,
  7 + PRIMARY KEY (aberrant_id)
  8 +)ENGINE=InnoDB DEFAULT CHARSET=utf8;
  9 +
  10 +INSERT INTO aberrant (aberrant_id, order_no, reason, created) VALUES (1, 3, 'ds01', '2018-06-27 16:37:39');
  11 +INSERT INTO aberrant (aberrant_id, order_no, reason, created) VALUES (2, 2, 'fagrgas', '2018-06-21 16:28:25');
  12 +INSERT INTO aberrant (aberrant_id, order_no, reason, created) VALUES (6, 4, 'fdsafagsa', '2018-06-28 09:40:35');
  13 +INSERT INTO aberrant (aberrant_id, order_no, reason, created) VALUES (7, 1, 'aaa', '2018-06-28 09:40:35');
  14 +INSERT INTO aberrant (aberrant_id, order_no, reason, created) VALUES (8, 2, '333', '2018-07-02 21:57:47');
  15 +INSERT INTO aberrant (aberrant_id, order_no, reason, created) VALUES (2323, 1, 'dddd', '2018-07-17 22:12:30');
  1 +package com.eck.auto;
  2 +
  3 +import org.springframework.boot.SpringApplication;
  4 +import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  5 +import org.springframework.boot.autoconfigure.SpringBootApplication;
  6 +import org.springframework.boot.autoconfigure.domain.EntityScan;
  7 +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
  8 +import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
  9 +import org.springframework.context.annotation.Import;
  10 +
  11 +@EnableAutoConfiguration
  12 +@EntityScan(basePackages = "com.eck.auto.model")
  13 +@SpringBootApplication
  14 +public class AppApplication {
  15 +
  16 + public static void main(String[] args) {
  17 + SpringApplication.run(AppApplication.class, args);
  18 + }
  19 +
  20 +}
  1 +package com.eck.auto;
  2 +
  3 +import org.springframework.context.ApplicationListener;
  4 +import org.springframework.context.event.ContextRefreshedEvent;
  5 +import org.springframework.stereotype.Component;
  6 +
  7 +@Component
  8 +public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
  9 +
  10 + @Override
  11 + public void onApplicationEvent(ContextRefreshedEvent event) {
  12 +
  13 + }
  14 +}
  1 +package com.eck.auto.config;
  2 +
  3 +import org.aspectj.lang.annotation.Aspect;
  4 +import org.aspectj.lang.annotation.Before;
  5 +import org.aspectj.lang.annotation.Pointcut;
  6 +import org.springframework.context.annotation.Configuration;
  7 +import org.springframework.core.annotation.Order;
  8 +import org.springframework.util.StringUtils;
  9 +import org.springframework.web.context.request.RequestContextHolder;
  10 +import org.springframework.web.context.request.ServletRequestAttributes;
  11 +
  12 +
  13 +@Aspect
  14 +@Order(1)
  15 +@Configuration
  16 +public class DataSourceAspect {
  17 + private static final String dsNo="dsNo";//数据库编号 从header中取
  18 +
  19 + /**
  20 + * 切入点,放在controller的每个方法上进行切入,更新数据源
  21 + */
  22 + @Pointcut("execution(* com.eck.auto.controller..*.*(..))")
  23 + private void anyMethod(){}//定义一个切入点
  24 + @Before("anyMethod()")
  25 + public void dataSourceChange()
  26 + {
  27 + //请求头head中获取对应数据库编号
  28 + String no = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader(dsNo);
  29 + System.out.print("当前数据源编号:"+no);
  30 + if(StringUtils.isEmpty(no)){
  31 + //TODO 根据业务抛异常
  32 + }
  33 + DataSourceHolder.setDataSource(no);
  34 + /*这里数据库项目编号来更改对应的数据源*/
  35 + }
  36 +}
  1 +package com.eck.auto.config;
  2 +
  3 +
  4 +public class DataSourceHolder {
  5 + //线程本地环境
  6 + private static final ThreadLocal<String> dataSources = new ThreadLocal<String>();
  7 + //设置数据源,动态切换,就是调用这个setDataSource方法
  8 + public static void setDataSource(String customerType) {
  9 + dataSources.set(customerType);
  10 + }
  11 + //获取数据源
  12 + public static String getDataSource() {
  13 + return (String) dataSources.get();
  14 + }
  15 + //清除数据源
  16 + public static void clearDataSource() {
  17 + dataSources.remove();
  18 + }
  19 +}
  1 +package com.eck.auto.config;
  2 +
  3 +import com.alibaba.druid.pool.DruidDataSource;
  4 +import org.springframework.context.annotation.Configuration;
  5 +import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
  6 +import javax.sql.DataSource;
  7 +import java.sql.SQLException;
  8 +import java.util.Map;
  9 +import java.util.concurrent.ConcurrentHashMap;
  10 +
  11 +@Configuration
  12 +public class DynamicDataSource extends AbstractRoutingDataSource {
  13 + /**
  14 + * 每次请求动态请求哪一个数据源
  15 + * @return
  16 + */
  17 + @Override
  18 + protected Object determineCurrentLookupKey() {
  19 + return DataSourceHolder.getDataSource();
  20 + }
  21 +
  22 + public DynamicDataSource(){
  23 + Map<Object, Object> dataSources=new ConcurrentHashMap<>();
  24 + for(int i=1;i<=4;i++){
  25 + DataSource dataSource = druidDataSource(i);
  26 + dataSources.put(String.valueOf(i),dataSource);
  27 + if(i==1){
  28 + super.setDefaultTargetDataSource(dataSource);
  29 + }
  30 + }
  31 + super.setTargetDataSources(dataSources);
  32 + }
  33 + /**
  34 + * 此处数据库信配置,可以来源于redis等,然后再初始化所有数据源
  35 + * 重点说明:一个DruidDataSource数据源,它里面本身就是线程池了,
  36 + * 所以我们不需要考虑线程池的问题
  37 + * @param no
  38 + * @return
  39 + */
  40 + public DataSource druidDataSource(int no) {
  41 + DruidDataSource datasource = new DruidDataSource();
  42 + datasource.setUrl("jdbc:mysql://localhost:3306/ds0"+no);
  43 + datasource.setUsername("root");
  44 + datasource.setPassword("123456");
  45 + datasource.setDriverClassName("com.mysql.jdbc.Driver");
  46 + datasource.setInitialSize(5);
  47 + datasource.setMinIdle(5);
  48 + datasource.setMaxActive(20);
  49 + //datasource.setDbType("com.alibaba.druid.pool.DruidDataSource");
  50 + datasource.setMaxWait(60000);
  51 + datasource.setTimeBetweenEvictionRunsMillis(60000);
  52 + datasource.setMinEvictableIdleTimeMillis(300000);
  53 + datasource.setValidationQuery("SELECT 1 FROM DUAL");
  54 + datasource.setTestWhileIdle(true);
  55 + datasource.setTestOnBorrow(false);
  56 + datasource.setTestOnReturn(false);
  57 + try {
  58 + datasource.setFilters("stat,wall,log4j");
  59 + } catch (SQLException e) {
  60 + e.printStackTrace();
  61 + }
  62 + return datasource;
  63 + }
  64 +}
  1 +package com.eck.auto.controller;
  2 +
  3 +
  4 +import com.eck.auto.config.DataSourceHolder;
  5 +import com.eck.auto.model.Aberrant;
  6 +import com.eck.auto.service.DataService;
  7 +import org.springframework.beans.factory.annotation.Autowired;
  8 +import org.springframework.stereotype.Controller;
  9 +import org.springframework.web.bind.annotation.RequestMapping;
  10 +import org.springframework.web.bind.annotation.RequestMethod;
  11 +import org.springframework.web.bind.annotation.RestController;
  12 +
  13 +import java.util.List;
  14 +
  15 +@RestController
  16 +@RequestMapping("/app")
  17 +public class DataController {
  18 +
  19 + @Autowired
  20 + private DataService dataService;
  21 +
  22 + @RequestMapping(value="/cc",method = RequestMethod.GET)
  23 + public List<Aberrant> cc(Integer id) {
  24 + List<Aberrant> list = dataService.find(id);
  25 + System.out.println(list);
  26 + return list;
  27 + }
  28 +
  29 + @RequestMapping(value="/cc1",method = RequestMethod.GET)
  30 + public List<Aberrant> cc1(Integer id) {
  31 + DataSourceHolder.setDataSource("1");
  32 + List<Aberrant> list = dataService.find(id);
  33 + System.out.println(list);
  34 + return list;
  35 + }
  36 + @RequestMapping(value="/cc2",method = RequestMethod.GET)
  37 + public List<Aberrant> cc2(Integer id) {
  38 + DataSourceHolder.setDataSource("2");
  39 + List<Aberrant> list = dataService.find(id);
  40 + System.out.println(list);
  41 + return list;
  42 + }
  43 + @RequestMapping(value="/cc3",method = RequestMethod.GET)
  44 + public List<Aberrant> cc3(Integer id) {
  45 + DataSourceHolder.setDataSource("3");
  46 + List<Aberrant> list = dataService.find(id);
  47 + System.out.println(list);
  48 + return list;
  49 + }
  50 +
  51 + @RequestMapping(value="/update",method = RequestMethod.GET)
  52 + public String update(Integer id) {
  53 + dataService.upate();
  54 + return "ok";
  55 + }
  56 +
  57 +}
  1 +package com.eck.auto.dao;
  2 +
  3 +
  4 +
  5 +
  6 +
  7 +import com.eck.auto.model.Aberrant;
  8 +
  9 +import java.util.List;
  10 +
  11 +public interface AberrantDao{
  12 +
  13 + List<Aberrant> findAll();
  14 + public int update();
  15 +}
  1 +package com.eck.auto.dao;
  2 +
  3 +/**
  4 + * Created by Administrator on 2018/7/21.
  5 + */
  6 +public interface DataDao {
  7 +}
  1 +package com.eck.auto.dao.impl;
  2 +
  3 +
  4 +import com.eck.auto.dao.AberrantDao;
  5 +import com.eck.auto.model.Aberrant;
  6 +import org.apache.commons.lang.StringUtils;
  7 +import org.springframework.stereotype.Repository;
  8 +
  9 +import javax.persistence.EntityManager;
  10 +import javax.persistence.PersistenceContext;
  11 +import javax.persistence.Query;
  12 +import java.util.List;
  13 +
  14 +@Repository
  15 +public class AberrantDaoImpl implements AberrantDao {
  16 +
  17 + @PersistenceContext
  18 + private EntityManager entityManager;
  19 +
  20 + @Override
  21 + public List<Aberrant> findAll() {
  22 +
  23 + String hql="from Aberrant where aberrantId=:aberrantId ";
  24 + Query query=entityManager.createQuery(hql.toString());
  25 + query.setParameter("aberrantId",1);
  26 + List<Aberrant> lists=query.getResultList();
  27 + if(lists.size()>0){
  28 + return query.getResultList();
  29 + }else{
  30 + return null;
  31 + }
  32 + }
  33 +
  34 +
  35 + public int update(){
  36 + String hql="update Aberrant set orderNo=88 where aberrantId=:aberrantId ";
  37 + Query query=entityManager.createQuery(hql.toString());
  38 + query.setParameter("aberrantId",1);
  39 + return query.executeUpdate();
  40 + }
  41 +
  42 +
  43 +}
  1 +package com.eck.auto.dao.impl;
  2 +
  3 +import com.eck.auto.dao.DataDao;
  4 +import org.springframework.stereotype.Repository;
  5 +
  6 +//@Repository
  7 +public class DataDaoImpl implements DataDao {
  8 +}
  1 +package com.eck.auto.exception;
  2 +import com.eck.auto.model.vo.ResultInfoVo;
  3 +import org.springframework.http.HttpStatus;
  4 +import org.springframework.http.ResponseEntity;
  5 +import org.springframework.web.bind.annotation.ControllerAdvice;
  6 +import org.springframework.web.bind.annotation.ExceptionHandler;
  7 +import org.springframework.web.bind.annotation.RestController;
  8 +
  9 +@RestController
  10 +@ControllerAdvice
  11 +public class ExceptionHandlers {
  12 +
  13 + @ExceptionHandler(MyException.class)
  14 + public ResponseEntity<ResultInfoVo> DataQualityException(MyException e) {
  15 + e.printStackTrace();
  16 + ResultInfoVo info = new ResultInfoVo(e.getHttpCode(),e.getCode(),e.getMessage());
  17 + return new ResponseEntity<ResultInfoVo>(info, HttpStatus.valueOf(e.getHttpCode()));
  18 +
  19 + }
  20 +
  21 + @ExceptionHandler(Exception.class)
  22 + public ResponseEntity<ResultInfoVo> Exception(Exception e) {
  23 + e.printStackTrace();
  24 + ResultInfoVo vo = null;
  25 + if(e instanceof NullPointerException) {
  26 + vo = new ResultInfoVo(HttpStatus.INTERNAL_SERVER_ERROR.value(),"InternalServerError", "空指针异常");
  27 + }else{
  28 + vo = new ResultInfoVo(HttpStatus.INTERNAL_SERVER_ERROR.value(),"InternalServerError",e.getMessage());
  29 + }
  30 + return new ResponseEntity<ResultInfoVo>(vo, HttpStatus.valueOf(500));
  31 + }
  32 +
  33 +
  34 +}
  1 +package com.eck.auto.exception;
  2 +
  3 +import org.apache.commons.logging.Log;
  4 +import org.apache.commons.logging.LogFactory;
  5 +
  6 +/**
  7 + *
  8 + * 统一处理错误异常消息格式
  9 + */
  10 +public class MyException extends RuntimeException {
  11 + private Log logger = LogFactory.getLog(getClass());
  12 + private int httpCode;//http错误码
  13 + private String code;//业务code:成都为success,失败为其它业务,如roleIdIsNull")
  14 + private String message;//错误详情
  15 + private Object data;//其它数据
  16 +
  17 +
  18 + public MyException(int httpCode, String code, String message) {
  19 + this.httpCode = httpCode;
  20 + this.code = code;
  21 + this.message = message;
  22 + }
  23 +
  24 + public int getHttpCode() {
  25 + return httpCode;
  26 + }
  27 +
  28 + public void setHttpCode(int httpCode) {
  29 + this.httpCode = httpCode;
  30 + }
  31 +
  32 + public String getCode() {
  33 + return code;
  34 + }
  35 +
  36 + public void setCode(String code) {
  37 + this.code = code;
  38 + }
  39 +
  40 + @Override
  41 + public String getMessage() {
  42 + return message;
  43 + }
  44 +
  45 + public void setMessage(String message) {
  46 + this.message = message;
  47 + }
  48 +
  49 + public Object getData() {
  50 + return data;
  51 + }
  52 +
  53 + public void setData(Object data) {
  54 + this.data = data;
  55 + }
  56 +
  57 + @Override
  58 + public String toString() {
  59 + String log=" httpCode:"+ httpCode +"\n code:"+code+"\n message:"+ message;
  60 + logger.debug(log);
  61 + return log;
  62 + }
  63 +}
  1 +package com.eck.auto.model;
  2 +
  3 +import javax.persistence.*;
  4 +import java.io.Serializable;
  5 +import java.util.Date;
  6 +
  7 +
  8 +/**
  9 + * The persistent class for the aberrant database table.
  10 + *
  11 + */
  12 +@Entity
  13 +@Table(name="aberrant")
  14 +public class Aberrant implements Serializable {
  15 + private static final long serialVersionUID = 1L;
  16 +
  17 + @Id
  18 + @GeneratedValue(strategy = GenerationType.IDENTITY)
  19 + @Column(name="aberrant_id")
  20 + private Integer aberrantId;
  21 +
  22 + @Temporal(TemporalType.TIMESTAMP)
  23 + private Date created;
  24 +
  25 + @Column(name="order_no")
  26 + private Integer orderNo;
  27 +
  28 + private String reason;
  29 +
  30 + public Integer getAberrantId() {
  31 + return this.aberrantId;
  32 + }
  33 +
  34 + public void setAberrantId(Integer aberrantId) {
  35 + this.aberrantId = aberrantId;
  36 + }
  37 +
  38 + public Date getCreated() {
  39 + return this.created;
  40 + }
  41 +
  42 + public void setCreated(Date created) {
  43 + this.created = created;
  44 + }
  45 +
  46 + public Integer getOrderNo() {
  47 + return this.orderNo;
  48 + }
  49 +
  50 + public void setOrderNo(Integer orderNo) {
  51 + this.orderNo = orderNo;
  52 + }
  53 +
  54 + public String getReason() {
  55 + return this.reason;
  56 + }
  57 +
  58 + public void setReason(String reason) {
  59 + this.reason = reason;
  60 + }
  61 +
  62 +
  63 +}
  1 +package com.eck.auto.model.vo;
  2 +
  3 +public class ResultInfoVo<T> {
  4 +
  5 + public static final String SUCCESS="success";
  6 + private Integer httpCode=200;//httpCode 成功为200
  7 + private String code="success";//业务code 成功为 success 失败为 其它业务编号,如paramIsNull
  8 + private String message="处理成功";//描述信息
  9 + public T data;//页数据
  10 +
  11 + public ResultInfoVo(){}
  12 +
  13 + public ResultInfoVo(T data) {
  14 + this.data = data;
  15 + }
  16 +
  17 + public ResultInfoVo(Integer httpCode, String code, String message) {
  18 + this.httpCode = httpCode;
  19 + this.code = code;
  20 + this.message = message;
  21 + }
  22 +
  23 + public ResultInfoVo(Integer httpCode, String code, String message, T data) {
  24 + this.httpCode = httpCode;
  25 + this.code = code;
  26 + this.message = message;
  27 + this.data = data;
  28 + }
  29 +
  30 + public Integer getHttpCode() {
  31 + return httpCode;
  32 + }
  33 +
  34 + public void setHttpCode(Integer httpCode) {
  35 + this.httpCode = httpCode;
  36 + }
  37 +
  38 + public String getCode() {
  39 + return code;
  40 + }
  41 +
  42 + public void setCode(String code) {
  43 + this.code = code;
  44 + }
  45 +
  46 + public String getMessage() {
  47 + return message;
  48 + }
  49 +
  50 + public void setMessage(String message) {
  51 + this.message = message;
  52 + }
  53 +
  54 + public T getData() {
  55 + return data;
  56 + }
  57 +
  58 + public void setData(T data) {
  59 + this.data = data;
  60 + }
  61 +}
  1 +package com.eck.auto.service;
  2 +
  3 +import com.eck.auto.model.Aberrant;
  4 +
  5 +import java.util.List;
  6 +
  7 +/**
  8 + * Created by Administrator on 2018/7/21.
  9 + */
  10 +public interface DataService {
  11 + public List<Aberrant> find(Integer id);
  12 + public void upate();
  13 +}
  1 +package com.eck.auto.service.impl;
  2 +
  3 +import com.eck.auto.dao.AberrantDao;
  4 +import com.eck.auto.dao.DataDao;
  5 +import com.eck.auto.exception.MyException;
  6 +import com.eck.auto.model.Aberrant;
  7 +import com.eck.auto.service.DataService;
  8 +import org.springframework.beans.factory.annotation.Autowired;
  9 +import org.springframework.http.HttpStatus;
  10 +import org.springframework.stereotype.Service;
  11 +import org.springframework.transaction.annotation.Transactional;
  12 +
  13 +import java.util.List;
  14 +
  15 +/**
  16 + * Created by Administrator on 2018/7/21.
  17 + */
  18 +@Service
  19 +public class DataServiceImpl implements DataService {
  20 +
  21 + //@Autowired
  22 + private DataDao dataDao;
  23 +
  24 + @Autowired
  25 + private AberrantDao aberrantDao;
  26 +
  27 +
  28 + public List<Aberrant> find(Integer id){
  29 + List<Aberrant> list = aberrantDao.findAll();
  30 + return list;
  31 + }
  32 +
  33 + /**
  34 + * 测试事务
  35 + */
  36 + @Transactional
  37 + public void upate() {
  38 + aberrantDao.update();
  39 + if(1==1){
  40 + throw new MyException(HttpStatus.OK.value(),"xxxxx","主动异常");
  41 + }
  42 + }
  43 +
  44 +}
  1 +package com.eck.auto.test;
  2 +
  3 +import com.eck.auto.utils.HttpRequest;
  4 +
  5 +/**
  6 + * Created by Administrator on 2018/7/22.
  7 + */
  8 +public class MyThread extends Thread {
  9 + int dsNo;
  10 + String ds;
  11 + String url;
  12 +
  13 + public MyThread(int no,String ds,String url){
  14 + this.dsNo =no;
  15 + this.ds=ds;
  16 + this.url=url;
  17 + }
  18 + @Override
  19 + public void run() {
  20 + for(int i = 0; i< dsNo; i++) {
  21 + String result1 = HttpRequest.sendGet(url);
  22 + System.out.println(ds + "===" + result1);
  23 + }
  24 + }
  25 +}
  1 +package com.eck.auto.test;
  2 +
  3 +import com.eck.auto.utils.HttpRequest;
  4 +
  5 +import java.util.Scanner;
  6 +
  7 +/**
  8 + * Created by Administrator on 2018/7/22.
  9 + */
  10 +public class Test {
  11 + public static void main(String[] args){
  12 + String url1="http://localhost:8080/app/hekf/1";
  13 + String url2="http://localhost:8080/all/lp/2";
  14 + MyThread mt1 = new MyThread(10000,"ds1",url1);
  15 + MyThread mt2 = new MyThread(10000,"ds2",url2);
  16 +
  17 + MyThread mt3 = new MyThread(10010,"ds3",url1);
  18 + mt1.start();
  19 + mt2.start();
  20 + mt3.start();
  21 + Scanner scanner = new Scanner(System.in);
  22 + while(scanner.hasNext()){
  23 + String str =scanner.next();
  24 + System.out.println("当前输入:"+str);
  25 + }
  26 + }
  27 +}
  1 +package com.eck.auto.utils;
  2 +
  3 +import java.io.BufferedReader;
  4 +import java.io.IOException;
  5 +import java.io.InputStreamReader;
  6 +import java.io.PrintWriter;
  7 +import java.net.URL;
  8 +import java.net.URLConnection;
  9 +import java.util.List;
  10 +import java.util.Map;
  11 +
  12 +public class HttpRequest {
  13 + /**
  14 + * 向指定URL发送GET方法的请求
  15 + *
  16 + * @param url
  17 + * 发送请求的URL
  18 + * @param param
  19 + * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  20 + * @return URL 所代表远程资源的响应结果
  21 + */
  22 + public static String sendGet(String url) {
  23 + String result = "";
  24 + BufferedReader in = null;
  25 + try {
  26 + String urlNameString = url;
  27 + URL realUrl = new URL(urlNameString);
  28 + // 打开和URL之间的连接
  29 + URLConnection connection = realUrl.openConnection();
  30 + // 设置通用的请求属性
  31 + connection.setRequestProperty("accept", "*/*");
  32 + connection.setRequestProperty("connection", "Keep-Alive");
  33 + connection.setRequestProperty("user-agent",
  34 + "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  35 + // 建立实际的连接
  36 + connection.connect();
  37 + // 获取所有响应头字段
  38 + Map<String, List<String>> map = connection.getHeaderFields();
  39 + // 遍历所有的响应头字段
  40 + for (String key : map.keySet()) {
  41 + System.out.println(key + "--->" + map.get(key));
  42 + }
  43 + // 定义 BufferedReader输入流来读取URL的响应
  44 + in = new BufferedReader(new InputStreamReader(
  45 + connection.getInputStream()));
  46 + String line;
  47 + while ((line = in.readLine()) != null) {
  48 + result += line;
  49 + }
  50 + } catch (Exception e) {
  51 + System.out.println("发送GET请求出现异常!" + e);
  52 + e.printStackTrace();
  53 + }
  54 + // 使用finally块来关闭输入流
  55 + finally {
  56 + try {
  57 + if (in != null) {
  58 + in.close();
  59 + }
  60 + } catch (Exception e2) {
  61 + e2.printStackTrace();
  62 + }
  63 + }
  64 + return result;
  65 + }
  66 +
  67 + /**
  68 + * 向指定 URL 发送POST方法的请求
  69 + *
  70 + * @param url
  71 + * 发送请求的 URL
  72 + * @param param
  73 + * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  74 + * @return 所代表远程资源的响应结果
  75 + */
  76 + public static String sendPost(String url, String param) {
  77 + PrintWriter out = null;
  78 + BufferedReader in = null;
  79 + String result = "";
  80 + try {
  81 + URL realUrl = new URL(url);
  82 + // 打开和URL之间的连接
  83 + URLConnection conn = realUrl.openConnection();
  84 + // 设置通用的请求属性
  85 + conn.setRequestProperty("accept", "*/*");
  86 + conn.setRequestProperty("connection", "Keep-Alive");
  87 + conn.setRequestProperty("user-agent",
  88 + "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  89 + // 发送POST请求必须设置如下两行
  90 + conn.setDoOutput(true);
  91 + conn.setDoInput(true);
  92 + // 获取URLConnection对象对应的输出流
  93 + out = new PrintWriter(conn.getOutputStream());
  94 + // 发送请求参数
  95 + out.print(param);
  96 + // flush输出流的缓冲
  97 + out.flush();
  98 + // 定义BufferedReader输入流来读取URL的响应
  99 + in = new BufferedReader(
  100 + new InputStreamReader(conn.getInputStream()));
  101 + String line;
  102 + while ((line = in.readLine()) != null) {
  103 + result += line;
  104 + }
  105 + } catch (Exception e) {
  106 + System.out.println("发送 POST 请求出现异常!"+e);
  107 + e.printStackTrace();
  108 + }
  109 + //使用finally块来关闭输出流、输入流
  110 + finally{
  111 + try{
  112 + if(out!=null){
  113 + out.close();
  114 + }
  115 + if(in!=null){
  116 + in.close();
  117 + }
  118 + }
  119 + catch(IOException ex){
  120 + ex.printStackTrace();
  121 + }
  122 + }
  123 + return result;
  124 + }
  125 +}
  1 +server:
  2 + port: 8082
  3 +spring:
  4 + application:
  5 + name: mydata
  6 + jpa:
  7 + show-sql: true
  8 + properties:
  9 + hibernate:
  10 + dialect: org.hibernate.dialect.MySQLDialect
  11 +
  12 +#durid登陆账号密码
  13 +durid:
  14 + login:
  15 + username: root
  16 + password: 123456
  1 +log4j.rootLogger=DEBUG,ERROR,consoleAppender,logfile
  2 +
  3 +# ConsoleAppender 输出
  4 +log4j.appender.consoleAppender=org.apache.log4j.ConsoleAppender
  5 +log4j.appender.consoleAppender.layout=org.apache.log4j.PatternLayout
  6 +log4j.appender.consoleAppender.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%l]-[%p] %m%n
  7 +
  8 +#文件输出:RollingFileAppender
  9 +log4j.appender.logfile=org.apache.log4j.RollingFileAppender
  10 +#保存log文件路径
  11 +log4j.appender.logfile.File=${catalina.home}\\logs\\insoft-log.txt
  12 +# 默认为true,添加到末尾,false在每次启动时进行覆盖
  13 +log4j.appender.logfile.Append = true
  14 +# 一个log文件的大小,超过这个大小就又会生成1个日志 # KB ,MB,GB
  15 +log4j.appender.logfile.MaxFileSize = 10MB
  16 +log4j.appender.logfile.ImmediateFlush=false
  17 +# 最多保存20个文件备份
  18 +log4j.appender.logfile.MaxBackupIndex = 20
  19 +# 输出文件的格式
  20 +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
  21 +log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n
  22 +
  23 +# Druid
  24 +log4j.logger.druid.sql=ERROR,consoleAppender,logfile,DEBUG
  25 +log4j.logger.druid.sql.DataSource=INFO,DEBUG,consoleAppender,logfile
  26 +log4j.logger.druid.sql.Connection=INFO,DEBUG,consoleAppender,logfile
  27 +log4j.logger.druid.sql.Statement=INFO,DEBUG,consoleAppender,logfile
  28 +log4j.logger.druid.sql.ResultSet=INFO,DEBUG,consoleAppender,logfile
  1 +package com;
  2 +
  3 +import static org.junit.Assert.assertTrue;
  4 +
  5 +import org.junit.Test;
  6 +
  7 +/**
  8 + * Unit test for simple App.
  9 + */
  10 +public class AppTest
  11 +{
  12 + /**
  13 + * Rigorous Test :-)
  14 + */
  15 + @Test
  16 + public void shouldAnswerWithTrue()
  17 + {
  18 + assertTrue( true );
  19 + }
  20 +}