Skip to main content

Redis pub/sub on Spring-Data


Center 에 MDM 으로 부터 Overseas 의 분산 서버로 master data 를 분산 배포하는 구조에 적용하려 함.


1. config

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

<bean id="connectionFactory"
 class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
 <property name="hostName" value="localhost" />
 <property name="port" value="7379" />
 <property name="password" value="deweyhong" />
</bean>

<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" />

<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" lazy-init="false">
<property name="connectionFactory" ref="connectionFactory" />
<property name="keySerializer" ref="stringRedisSerializer" />
<property name="hashKeySerializer" ref="stringRedisSerializer" />
<property name="valueSerializer" ref="stringRedisSerializer" />
</bean>

<bean id="messageListener" class="org.springframework.data.redis.listener.adapter.MessageListenerAdapter">
    <constructor-arg>
        <bean class="lhf.common.redis.service.support.RedisMessageListener"/>
    </constructor-arg>
</bean>
<bean id="redisMessageListenerContainer" class="org.springframework.data.redis.listener.RedisMessageListenerContainer">
    <property name="connectionFactory" ref="connectionFactory"/>
    <property name="messageListeners">
      <!-- map of listeners and their associated topics (channels or/and patterns) -->
      <map>
        <entry key-ref="messageListener">
            <bean class="org.springframework.data.redis.listener.ChannelTopic">
               <constructor-arg value="USER"/>
            </bean>
        </entry>
      </map>
    </property>
 </bean>

</beans>

2. publisher (marshalling 적용)

    public void publishData(Object data){
        try{
            JAXBContext jaxbContext;
            if(data instanceof Data){
                jaxbContext = JAXBContext.newInstance(Data.class);
                Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
                jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                jaxbMarshaller.marshal((Data)data, (OutputStream)output);
                redisTemplate.convertAndSend(((Data)data).getObjectKey(), data);
            }else if(data instanceof Lists){
                jaxbContext = JAXBContext.newInstance(Lists.class, Data.class);
                Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
                jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                jaxbMarshaller.marshal((Lists)data, (OutputStream)output);
                redisTemplate.convertAndSend(((Lists<Data>)data).getValues().get(0).getObjectKey(), output.toString());
            }
        }catch(JAXBException e){
            e.printStackTrace();
        }
    }


3. 호출

            Lists<Data> userList = new Lists<Data>();
            userList.getValues().add(user1);
            userList.getValues().add(user2);
         
            // onMessage  호출
            service.publishData(userList);  


4. listener (unmarshalling 적용)

public class RedisMessageListener implements MessageListener {

    public void onMessage(final Message message, final byte[] pattern){
        try{
            String strData = message.toString();
            strData = "<?" + strData.substring(strData.indexOf("xml "), strData.length()); // 깨짐 방지
            System.out.println("Message received: " + strData);
            if(strData.indexOf("<lists>") == -1){
                JAXBContext jaxbContext = JAXBContext.newInstance(Data.class);
                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                Data data = (Data)jaxbUnmarshaller.unmarshal(createInputStream(strData, null));
            }else{
                JAXBContext jaxbContext = JAXBContext.newInstance(Lists.class, Data.class);
                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                Lists data = (Lists)jaxbUnmarshaller.unmarshal(createInputStream(strData, null));
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    private InputStream createInputStream(String s, String charset) throws java.io.UnsupportedEncodingException{
        if(charset != null) {
            return new ByteArrayInputStream(s.getBytes(charset));
        } else {
            return new ByteArrayInputStream(s.getBytes());
        }
    }
}

=> RedisMessageListener 으로 들어온 data 적절히 활용





Comments

Popular posts from this blog

DevOps JD's required skills from LinkedIn

From some of DevOps JD on linkedIn, I realised that DeveOps should be the leader of the organization. https://docs.google.com/spreadsheets/d/1P520nH0pYcAdN0rJcnMQqsgu9cV9GdknztJ92J8l7-s/pubhtml DevOps' Required Skills From LinkedIn on 8/30/16: DevOps should be the leader of the company! Yahoo Netflix Samsung Salesforce Fortinet SUM OS admin UNIX systems Unix platforms Linux administrator Linux VMs Docker VMs VMware, OpenStack, Hyper-V Openstack, KVM, VMWare Version control version control systems Git, SVN Cloud Amazon AWS AWS AWS, Azure DB MySql Oracle, MySQL, NoSQL Mysql administration and strong command of SQL MySQL RabbitMQ MySql, MongoDB, Redis, Oracle, ProgreSQL N/W TCP/IP networking, DNS, HTTP NAS Understanding of network stack, network tuning, subnet/VLANs. HAProxy, DNS, IPTable Script Lang Shell, Perl, Python, Ruby, PHP bash Python, Bash/tcsh a scripting language: Perl, Python and Unix Shell preferred Python, Perl, Ruby Python, Ruby, Shell, PHP Web LAMP stack

Ubuntu GUI with VNC on Xenserver

Xenserver 에서 Ubuntu GUI 를 쓰기 위해서는 VNC 가 답인 듯... Installing Ubuntu Gnome GUI on Ubuntu Server 12.10 with VNC Update Repositories # apt-get update Install gnome and vnc: # apt-get install gnome-core vnc4server Start VNC Server: # vncserver (You’ll then be prompted to create and verify a new VNC connect password) Kill the currently running VNC Session: # vncserver -kill :1 Edit VNC startup config file: # vim .vnc/xstartup Uncomment the following line: unset SESSION_MANAGER Add the following line: gnome-session --session=gnome-classic & Comment Out the following two lines: x-terminal-emulator -geometry 1280x1024+10+10 -ls -title "$VNCDESKTOP Desktop" & x-window-manager & End result should look like: #!/bin/sh # Uncomment the following two lines for normal desktop: unset SESSION_MANAGER # exec /etc/X11/xinit/xinitrc gnome-session --session=gnome-classic & [ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup [ -r $HOME/

Install CoreOs on linode without VM

Install CoreOs on linode without VM 1. Add a Linode 2. Create a new Disk   CoreOS 3. Rescue > Reboot into Rescue Mode 4. Remote Access   Launch Lish Console 5. make an install script cat <<'EOF1' > install.sh # add needed package sudo apt-get update sudo apt-get install -y curl wget whois sudo apt-get install -y ca-certificates #sudo apt-get install gawk -y # get discovery url discoveryUrl=`curl https://discovery.etcd.io/new` # write cloud-config.yml cat <<EOF2 > cloud-config.yml #cloud-config users:   - name: core     groups:       - sudo       - docker coreos:   etcd:     name: node01     discovery: $discoveryUrl hostname: node01 EOF2 # get the coreos installation script #wget https://raw.github.com/coreos/init/master/bin/coreos-install wget https://raw.githubusercontent.com/coreos/init/master/bin/coreos-install # run installation chmod 755 coreos-install sudo ./coreos-install \       -d /dev/sda \       -