로그성 DB INSERT로 인해서 전체적인 DB성능 이슈가 발생하면서 어플리케이션까지 서능에 영향이 미치는 상황이 발생하였다.
처음에는 Logging 라이브러리를 활용하여 Text형태로 쌓아놓고 한가한 시간에 배치로 DB에 INSERT하려고 하다가 공부 겸 JMS(java message service)를 적용해보기로 하였다.
Message Queue 관련 방법은 여러가지가 있던데 선택은 Apache ActiveMQ 를 선택 하였다.
관련 장단점에 대해서는 인터넷 참고!!
우선 Apache ActiveMQ 설치
context-jms.xml
MemberMessageConverter.java
package pe.kr.ddakker.jms; import javax.jms.JMSException; import javax.jms.MapMessage; import javax.jms.Message; import javax.jms.Session; import org.springframework.jms.support.converter.MessageConversionException; import org.springframework.jms.support.converter.MessageConverter; public class MemberMessageConverter implements MessageConverter { public MemberMessageConverter(){} @Override public Object fromMessage(Message message) throws JMSException, MessageConversionException { if(!(message instanceof MapMessage)){ throw new MessageConversionException("Messaeg isn't a MapMessage"); } MapMessage mapMessage = (MapMessage) message; Member member = new Member(); member.setName(mapMessage.getString("name")); member.setEmail(mapMessage.getString("email")); return member; } @Override public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException { if(!(object instanceof Member)){ throw new MessageConversionException("Messaeg isn't a Member"); } Member member = (Member) object; MapMessage message = session.createMapMessage(); message.setString("name", member.getName()); message.setString("email", member.getEmail()); return message; } }
ReceiverMessageListenerImpl.java
package pe.kr.ddakker.jms; import javax.annotation.Resource; import javax.jms.Message; import javax.jms.MessageListener; import org.springframework.jms.support.converter.MessageConverter; import org.springframework.stereotype.Component; @Component public class ReceiverMessageListenerImpl implements MessageListener { @Resource private MessageConverter memberConverter; @Override public void onMessage(Message message) { Member member = null; try { member = (Member) memberConverter.fromMessage(message); if (member != null) { System.out.println("member.getEmail(): " + member.getEmail()); } } catch (Exception e) { System.err.println(e); } } }
JmsTest .java
package pe.kr.ddakker.jms; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.jms.core.JmsTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath*:config/spring/context-jms.xml"}) public class JmsTest { @Resource private JmsTemplate jmsTemplate; @Test public void test() { for (int i = 0; i < 5; i++) { Member member = new Member(); member.setName("ddakker" + i); member.setEmail("ddakker" + i + "@gmail.com"); jmsTemplate.convertAndSend(member); } } }