반응형

다음과 같은 에러가 나타날 때 처리
com.enrise.framework.exception.DSSqlException: Communications link failure due to underlying exception:

** BEGIN NESTED EXCEPTION **

java.net.SocketException
MESSAGE: Software caused connection abort: socket write error

STACKTRACE:

java.net.SocketException: Software caused connection abort: socket write error
 at java.net.SocketOutputStream.socketWrite0(Native Method)
 at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
 at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
 at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)
 at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123)
 at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:2744)
 at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1612)
 at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
 at com.mysql.jdbc.Connection.execSQL(Connection.java:3283)
 at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1332)
 at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1467)
 at org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:93)
 at com.enrise.framework.db.query.LoggableStatement.executeQuery(LoggableStatement.java:231)
 at com.enrise.framework.db.query.QueryManager.executeQueryOne(QueryManager.java:241)
 at com.enrise.framework.db.query.QueryManager.executeQueryOne(QueryManager.java:227)
 at com.enrise.ds.am.dao.AmUserDAO.getUserByUserID(AmUserDAO.java:213)
 at com.enrise.ds.am.business.AmUserBusiness.getUserByUserID(AmUserBusiness.java:156)
 at com.enrise.ds.common.command.CoLoginCommand.execute(CoLoginCommand.java:224)
 at com.enrise.ds.common.servlet.HTTPServices.doPost(HTTPServices.java:115)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

......


해결 -> http://amitcodes.wordpress.com/2008/07/26/16/
위에 링크를 한 블로거의 설명 및 해결 방법 이다.
Cause:
 MySQL server has a default timeout period after which it terminates the idle connections. This period is 8 hours by default. Now heres what happens. The dbcp creates a set of connections to database when the servlet container / application server starts up. If the connections are not used for the tinmeout period, the MySQL server assumes these to be dead connections and terminates them. The dbcp, however, is unaware of the fact that the connections have been terminated. So when a connection is demended from the connection-pool, these dead connections are returned and when a call is made on these dead connections  *BOOM*  you the java.net.SocketException: Broken pipe exception. Ok  so whats the fix ??

Fix: If only the connection pool could check if the the connection it is about to return is live or not, the porblem is fixed. This can be done in apache-common-dbcp (I know this one coz I used it, please look into documentation of the connection-pool you are using). Heres how you do it: You add the following properties to dbcp configuration.

·        validationQuery=SELECT 1

·        testOnBorrow=true

And that does the trick.

How it works:

·        Before returning the connection from pool to the application, dbcp runs the SELECT 1  query on the connection to see it it is still live. Thats the job of validationQuery.

·        As for testOnBorrow, you tell dbcp to perform the check before returning the connection to application.

For more details refer to the apache-common-dbcp configuration manual hereThe apache-commons-dbcp config:

view source

print?

01

<Resource   name="jdbc/cooldatabase"

02

            description="Strandls.com license database"

03

            auth="Container"

04

            type="javax.sql.DataSource"

05

            factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"

06

            driverClassName="com.mysql.jdbc.Driver"

07

            url="jdbc:mysql://localhost:3306/cooldatabase?autoReconnect=true"

08

            username="cooluser"

09

            password="coolpassword"

10

            initialSize="0"

11

            maxActive="20"

12

            maxIdle="10"

13

            minIdle="0"

14

            maxWait="-1"

15

            validationQuery="SELECT 1"

16

            testOnBorrow="true"

17

            poolPreparedStatements="true"

18

            removeAbandoned="true"

19

            removeAbandonedTimeout="60"

20

            logAbandoned="true"/>

The complete stacktrace:

[ERROR] 12:27 (JDBCExceptionReporter.java:logExceptions:78)Communications link failure due to underlying exception:

 

** BEGIN NESTED EXCEPTION **

 

java.net.SocketExceptionMESSAGE: Broken pipe

 

STACKTRACE:

java.net.SocketException: Broken pipeat

java.net.SocketOutputStream.socketWrite0(Native Method)

at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)

at java.net.SocketOutputStream.write(SocketOutputStream.java:136)

at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)

at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123)

at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:2689)

at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:2618)

at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1551).....

 

 

--------------------------------------------------------------------------------------------------------------------------

 요약 하자면

원인: MySQL은 디폴트 타임아웃 값을 가지고 있다만약 커넥션이 생성되고이 타임아웃 기간이 지날 동안 사용되지 않는다면 이 커넥션은 끊긴 것으로 간주하고 커넥션을 종료한다하지만 dbcp는 커넥션이 끊어졌음을 알아채지 못하고커넥션 요청이 있을 때 연결이 끊긴 커넥션을 돌려준다그래서 에러가 발생한다.

 

수정: DBCP configuration 에 다음 사항을 추가한다.

·        validationQuery=SELECT 1

·        testOnBorrow=true

·        url="jdbc:mysql://localhost:3306/dbPoolName?autoReconnect=true

동작하는 방식

l  어플리케이션에 커넥션을 리턴하기 전에 dbcp는 “SELECT 1”쿼리를 실행해서 해당 커넥션이 살아있는지 확인한다이 작업이 ‘validationQuery’ 이다.

l  testOnBorrow 를 설정함으로써 커넥션을 어플리케이션에 돌려주기 전에 dbcp가 체크하도록 한다.

 

 

 < 설 명 >
'autoReconnect'옵션을 주게 되면, 커넥션에 문제가 있을 경우 다시 접속하게 된다.
그러나, 이 경우에도 끊어진 후 처음 한번의 시도는 실패가 나게 된다(이때 문제가 있다는것을 알게 되는 것이므로..).
이때는 추가적인 DBCP옵션인 'validationQuery'값의 설정으로 해결 가능하다.
validationQuery="select 1" => MySQL의 경우
validationQuery="select 1 from dual" => Oracle의 경우


maxActive 커넥션 풀이 제공할 최대 커넥션 개수 
maxIdle 사용되지 않고 풀에 저장될 수 있는 최대 커넥션 개수. 음수일 경우 제한이 없다. 
maxWait whenExhaustedAction 속성의 값이 1일 때 사용되는 대기 시간. 단위는 1/1000초이며, 0 보다 작을 경우 무한히 대기한다. 
testOnBorrow true일 경우 커넥션 풀에서 커넥션을 가져올 때 커넥션이 유효한지의 여부를 검사한다. 
testWhileIdle true일 경우 비활성화 커넥션을 추출할 때 커넥션이 유효한지의 여부를 검사해서 유효하지 않은 커넥션은 풀에서 제거한다. 
timeBetweenEvctionRunsMillis 사용되지 않은 커넥션을 추출하는 쓰레드의 실행 주기를 지정한다. 양수가 아닐 경우 실행되지 않는다. 단위는 1/1000 초이다. 
minEvictableIdleTimeMillis 사용되지 않는 커넥션을 추출할 때 이 속성에서 지정한 시간 이상 비활성화 상태인 커넥션만 추출한다. 양수가 아닌 경우 비활성화된 시간으로는 풀에서 제거되지 않는다. 시간 단위는 1/1000초이다. 



출처 : 

http://invincure.tistory.com/entry/%EC%BB%A4%EB%84%A5%EC%85%98-%ED%92%80-%EC%9D%B4%EC%9A%A9%EC%8B%9C-DB-%EC%BB%A4%EB%84%A5%EC%85%98-%EC%97%90%EB%9F%AC

'JAVA > Spring' 카테고리의 다른 글

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener  (0) 2016.06.02
Spring log4j SQL 직관적으로 보기  (0) 2016.06.02
[Spring] MVC 예제  (0) 2014.11.18
[Spring] MCV  (0) 2014.11.18
[Spring] AOP  (0) 2014.11.18
반응형
package com.sangjun.mvc.controller;

import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.*;

import com.sangjun.mvc.dto.*;

//Controller 를 만들기 위한 annotation
//annotation이 없으면 요청이 와도 동작하지 않습니다.
@Controller
public class HelloController {
	
	
	@RequestMapping("/index.do")
	public ModelAndView index(){
		ModelAndView mav = new ModelAndView();
		
		//넘겨줄 데이터 저장
		mav.addObject("data","데이터!!!!!!!");
		//출력할 뷰 파일 이름 설정
		mav.setViewName("./view/index.jsp");
		return mav;
	}
	
	//매개변수로 dto 클래스 타입을 1개 작성하면
	//요청한 쪽의 파라미터가 대입되서 옵니다.
	@RequestMapping("/form.do")
	public ModelAndView form(@ModelAttribute("aaa") Article param){
		System.out.println("제목: "+param.getSubject() +
				"\n"+"내용 : "+param.getContent());
		
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/view/result.jsp");
		return mav;
	}

}

20141022MVC2.zip

'JAVA > Spring' 카테고리의 다른 글

Spring log4j SQL 직관적으로 보기  (0) 2016.06.02
커넥션 풀 이용시 DB 커넥션 에러  (0) 2015.10.05
[Spring] MCV  (0) 2014.11.18
[Spring] AOP  (0) 2014.11.18
[Spring] Message  (0) 2014.11.18
반응형
package com.choongang.controller;

import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.*;


@Controller
public class HelloController {
	
	//hello.do 요청이 오면 아래 메서드를 호출
	@RequestMapping("/hello.do")
	public ModelAndView hello(){
		
		ModelAndView mav = new ModelAndView();
		//출력할 뷰 이름을 설정
		mav.setViewName("hello");
		//뷰 파일에게 넘겨줄 데이터 자장 - 실제로는 request 객체에 저장됩니다.
		mav.addObject("greeting","안녕하세요 스프링 mvc 하는중입니다.");
		return mav;
	}

}

20141022_MVC.zip

'JAVA > Spring' 카테고리의 다른 글

커넥션 풀 이용시 DB 커넥션 에러  (0) 2015.10.05
[Spring] MVC 예제  (0) 2014.11.18
[Spring] AOP  (0) 2014.11.18
[Spring] Message  (0) 2014.11.18
[Spring] DI oracle (데이터베이스 접속하기)  (0) 2014.11.18
반응형

'JAVA > Spring' 카테고리의 다른 글

[Spring] MVC 예제  (0) 2014.11.18
[Spring] MCV  (0) 2014.11.18
[Spring] Message  (0) 2014.11.18
[Spring] DI oracle (데이터베이스 접속하기)  (0) 2014.11.18
[Spring] message 언어 선택  (0) 2014.11.18
반응형

'JAVA > Spring' 카테고리의 다른 글

[Spring] MCV  (0) 2014.11.18
[Spring] AOP  (0) 2014.11.18
[Spring] DI oracle (데이터베이스 접속하기)  (0) 2014.11.18
[Spring] message 언어 선택  (0) 2014.11.18
[spring] 팩토리 클래스 찾아서 메서드 호출하기( IOC )  (0) 2014.11.18
반응형

Dao.java


package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import dto.Member;

public class Dao {

	// 데이터베이스 연동에 필요한 4가지 정보를 저장할 변수
	private String driver;
	private String url;
	private String user;
	private String password;

	// driver는 생성자에서 넘겨받을 것입니다.
	public Dao(String driver) {
		super();
		this.driver = driver;
	}

	// url, user, password는 프로퍼티로 만들어서 나중에 대입받을 수 있도록 생성
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	// 실제 작업을 수행하는 메서드
	public void task() {
		Connection con = null;
		// sql 문장을 수행하기 위한 인터페이스
		PreparedStatement ps1 = null;
		PreparedStatement ps2 = null;
		// select 문장의 결과를 저장하기 위한 변수
		ResultSet rs = null;

		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			con = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		Member user = new Member();
		user.setId("MoonRiver111");
		user.setName("Jesica111");
		user.setPassword("Newziland111");
		try {
			ps1 = con
					.prepareStatement("insert into members(id, name, password) values(?,?,?)");
			ps1.setString(1, user.getId());
			ps1.setString(2, user.getName());
			ps1.setString(3, user.getPassword());
			ps1.executeUpdate();

		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}

		try {
			ps2 = con.prepareStatement("select * from members where id = ?");
			ps2.setString(1, "MoonRiver");
			rs = ps2.executeQuery();
			if (rs.next()) {
				Member user1 = new Member();
				user1.setId(rs.getString("id"));
				user1.setName(rs.getString("name"));
				user1.setPassword(rs.getString("password"));
				System.out.println(user1);
			} else {
				System.out.println("데이터가 없습니다.");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

}


Main.java


package dao;

import org.springframework.context.support.GenericXmlApplicationContext;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		GenericXmlApplicationContext context = 
				new GenericXmlApplicationContext("applicationContext.xml");

		Dao dao = context.getBean("Dao",Dao.class);
		
		dao.task();
	}

}



Member.java


package dto;

import java.io.Serializable;

public class Member implements Serializable {

	private String id;
	private String name;
	private String password;

	//빈 객체를 생성할때
	public Member() {
		super();
		// TODO Auto-generated constructor stub
	}

	
	public Member(String id, String name, String password) {
		super();
		this.id = id;
		this.name = name;
		this.password = password;
	}

	
	//접근자 메서드(getter, setter): 멤버 변수를 실제로 사용할 때 호출하는 메서드
	//setter가 있을때는 property 또는 attribute라고 하기도 합니다.
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}


	@Override
	public String toString() {
		return "Member [id=" + id + ", name=" + name + ", password=" + password
				+ "]";
	}
	
	

}


applicationContext.xml





   

   
   
      
         oracle.jdbc.driver.OracleDriver
      
   
   
   
      
         boxer
      
      
         boxing
      
      
         Haglar
      
   



'JAVA > Spring' 카테고리의 다른 글

[Spring] MCV  (0) 2014.11.18
[Spring] AOP  (0) 2014.11.18
[Spring] Message  (0) 2014.11.18
[Spring] message 언어 선택  (0) 2014.11.18
[spring] 팩토리 클래스 찾아서 메서드 호출하기( IOC )  (0) 2014.11.18
반응형

Data.java


package message;

public class Data {
	private String name;
	private int num;

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Data [name=" + name + ", num=" + num + "]";
	}


}


Main.java


package message;

import org.springframework.context.support.GenericXmlApplicationContext;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		GenericXmlApplicationContext context = new GenericXmlApplicationContext(
				"message/applicationContext.xml");

		MessageBean mb = context.getBean("insa", MessageBeanEn.class);
		mb.greeting("키키키");

		String str = context.getBean("str", String.class);
		System.out.println("Str: " + str);
		
		Data data = context.getBean("data",Data.class);
		
		data.setName("으악으각");
		
		System.out.println("데이터: "+data);

	}

}


MessageBean.java


package message;

public interface MessageBean {
	public void greeting(String name);
}


MessageBeanEn.java


package message;

public class MessageBeanEn implements MessageBean{

	@Override
	public void greeting(String name) {
		// TODO Auto-generated method stub
		System.out.println("Hello ~ " + name);
		
	}

}



MessageBeanKr.java


package message;

public class MessageBeanKr implements MessageBean{

	@Override
	public void greeting(String name) {
		// TODO Auto-generated method stub
		System.out.println("안녕하세요~ "+name+"님");
		
	}

}


applicationContext.xml






	

	
		
			안녕안녕 키키키키킼
		
	

	
		
			이상주누주준
		
		
			123123
		

	




20141015_Spring_message.zip

'JAVA > Spring' 카테고리의 다른 글

[Spring] MCV  (0) 2014.11.18
[Spring] AOP  (0) 2014.11.18
[Spring] Message  (0) 2014.11.18
[Spring] DI oracle (데이터베이스 접속하기)  (0) 2014.11.18
[spring] 팩토리 클래스 찾아서 메서드 호출하기( IOC )  (0) 2014.11.18
반응형


20141015_Spring_IOC.zip

Main.java


package project_1;

import java.sql.Date;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

public class Main {

	public static void main(String[] args) {

		// Project_method obj = Obj_Factory.create();

		// 스프링의 팩토리 클래스 찾아오기
		// AnnotationConfigApplicationContext context =
		// new AnnotationConfigApplicationContext(Obj_Factory.class);

		// 팩토리 클래스에서 팩토리 메서드를 호출
		// 두번째 매개변수는 팩토리 메서드의 리턴타입입니다.
		// Project_method obj = context.getBean("create",Project_method.class);
		// Project_method obj1 = context.getBean("create",Project_method.class);

		// System.out.println(obj.hashCode() +" : "+obj1.hashCode());

		// project.xml에 있는 create라는 아이디를 가진 bean 태그 호출해서
		// Project_method 클래스 타입의 객체 주소를 obj에 대입
		GenericXmlApplicationContext context = new GenericXmlApplicationContext(
				"project_1/project_1.xml");

		Project_method obj = context.getBean("create", Project_method.class);
		//Date obj1 = context.getBean("today",Date.class);
		
		
		boolean result = obj.prime(7);

		if (result) {
			System.out.println("소수");
		} else
			System.out.println("소수 아님");
		
		Date obj1 = context.getBean("today", Date.class);
		System.out.println("오늘!: "+obj1);
		

//		String str = context.getBean("build", String.class);
//		System.out.println(str);

	}

}


Obj_Factory.java


package project_1;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

//스프링의 팩토리 클래스로 변환
@Configuration
public class Obj_Factory {

	// Method 클래스의 객체를 생성해주는 메서드
	//스프링의 팩토리 메서드로 변환
	@Bean
	static public Project_method create() {
		return new Project_method();
	}
	
	@Bean
	static public String build() {
		return new String("Hello world");
	}

}


Project_method.java


package project_1;

public class Project_method {
	
	// 정수를 매기변수로 받아서 소수인지 판별해주는 메서드
	// 소수는 2부터 자기 자신의 절반까지 나누어 떨어지지 않으면 소수
	public boolean prime(int index) {
		boolean result = true;
		for (int i = 2; i < index/2; i++) {
			if(index % i == 0){
				result = false;
				break;
			}
		}
		return result;
	}

}


project_1.xml





	
	

	
	





'JAVA > Spring' 카테고리의 다른 글

[Spring] MCV  (0) 2014.11.18
[Spring] AOP  (0) 2014.11.18
[Spring] Message  (0) 2014.11.18
[Spring] DI oracle (데이터베이스 접속하기)  (0) 2014.11.18
[Spring] message 언어 선택  (0) 2014.11.18

+ Recent posts