2015년 9월 16일 수요일

.NET Framework 4.5.2로 개발했다가. 4.0로... 내림

최근에 윈도우 어플을 개발할 일이 생겼다.

.NET 4.5부터 async 문법이 새로 들어갔다 해서.. 이왕 하는거 4.5.2로... 만들기로 했다.
오...... 엄청나게 편리하다.!!

async, await 두개가 중요하다.
특히 UI프로그램에서 background thread와 main thread와의 동기화를 쉽게 지원한다.

아래는 id/pwd를 입력받아서 서버통신으로 인증을 진행하는 코드다.


private async void btnLogin_Click(object sender, RoutedEventArgs e)
{
    string id = tbEmail.Text;
    string pwd = tbPassword.Password;

    SetControlEnableState(false);
    bool isSuccess = await Task.Run<bool>(() =>
    {
        try
        {
                    // 여기가 네트워크 통신을 하는 부분이다.
            _dataCore.DoLogin(id, pwd);
            return true;
        }
        catch (Exception x)
        {
            ErrorHandler.ErrorDump(x, true);
            return false;
        }
        });

    if (!isSuccess)
    {
        SetControlEnableState(true);
        return;
    }
}

보면 알겠지만 client이벤트에서 바로 ... 별도 쓰레드 동기화 없이.. 로그인 처리를 모두 완료했다.


오늘 테스트를 진행하는데...
.NET Framework 4.5 깔린... PC가.. 많이 없네.....

... 그래서.. 4.0으로.. BackgroundWorker 사용해서 재개발했다...

그지 같네... (화면이 세개인 프로그램이라 다행)

2015년 9월 15일 화요일

디지탈오션에 서버 셋팅기 (centos 6.7)


친구랑 개발하는 간단한 쪽지앱의 서버로 사용할 서버를 구축했다.
물론 나는 잘 모른다 모든건 다 구글을 통해..

1. SWAP 메모리 할당
참고) https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-centos-6

dd if=/dev/zero of=/swapfile bs=1024 count=2048k
mkswap /swapfile
swapon /swapfile
chown root:root /swapfile 
chmod 0600 /swapfile


아래 내용을 /etc/fstab 에 붙인다.

/swapfile          swap            swap    defaults        0 0



2. 서버 시간을 KST 로 바꿈 & rdate 설치

ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime
yum install rdate



3. java 1.7설치 rpm
http://www.oracle.com/technetwork/java/javase/downloads/jre7-downloads-1880261.html
위에서 64비트 linux용으로 다운받는다.

rpm -ivh jre-7u80-linux-x64.rpm


4. 위와 같은 방법으로 rabbitMQ 서버도 설치

rpm -ivh erlang-17.4-1.el6.x86_64.rpm
rpm -ivh rabbitmq-server-3.4.4-1.noarch.rpm


/etc/rabbitmq/rabbitmq-env.conf 파일 만들고 nodename 지정

NODENAME=samplenode


관리자 페이지 플러그인 활성화 & 서버 시작

rabbitmq-plugins enable rabbitmq_management
rabbitmq-server -detached




사용자 추가, id/pwd 지정하기 권한 주기
참고) https://www.rabbitmq.com/man/rabbitmqctl.1.man.html#

rabbitmqctl add_user {username} {password} 
rabbitmqctl set_user_tags {username} administrator 


http://hostname:15672/ 에 접속하여 admin메뉴에서 guest 계정 삭제
신규 worker 계정 추가


5. tomcat 7 설치
tar 다운로드 하여 /usr/local/ 에 압축을 풀고.

ln -s apache-tomcat-7.0.57 tomcat


6. mariadb 설치
http://zetawiki.com/wiki/%EB%A6%AC%EB%88%85%EC%8A%A4_MariaDB_%EC%84%A4%EC%B9%98 참고
아래 파일을 생성하고 내용을 작성
/etc/yum.repos.d/MariaDB.repoMariaDB.repo


[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/5.5/centos6-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1



yum install MariaDB-server MariaDB-client

#나중에 추가됨 (기본 설정 파일 적용)
cp /usr/share/mysql/my-medium.cnf /etc/my.cnf


7. apache 설치

yum install httpd
yum install mod_ssl


8. iptables 설정
아래 좋은 글이 있어 참고하여 아래와 같이 작성 했다.
출처) http://webdir.tistory.com/170


#!/bin/bash
# iptables 설정 자동화 스크립트
# 입맛에 따라 수정해서 사용합시다.
iptables -F

# TCP 포트 22번을 SSH 접속을 위해 허용
# 원격 접속을 위해 먼저 설정합니다
iptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT

# 기본 정책을 설정합니다
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# localhost 접속 허용
iptables -A INPUT -i lo -j ACCEPT

# established and related 접속을 허용
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# 기타 사용하는 포트 허용
# -s sourceIP 를 추가 하여 특정 아이피만 가능하도록 할 수 있다.
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 8080 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -p tcp --dport 3306 -j ACCEPT
iptables -A INPUT -p tcp --dport 15672 -j ACCEPT

# 설정을 저장
/sbin/service iptables save

# 설정한 내용을 출력
iptables -L -v

2015년 8월 27일 목요일

spring batch 사용

최근에 spring-batch를 사용해 봤는데.. 결과는 성공적 특히 트랜잭션commit size와 read size를 따로 지정할 수 있다는게 좋은것 같다.

쿼리나 기타 로직보다 아래 설정이 중요한 듯 하여 아래 설정을 기록으로 남긴다.

job에 대해서 요약하면
# reader에서 데이타를 읽어서 process 에서 처리 하고 writer로 결과를 기록 한다.

물론 위 설정 외에 각 시작 구간마다 이벤트를 받아 처리 할 수 있는 listener 같은 것도 제공한다.

reader, writer는 커스텀 하지 않고 mybatis에서 기본으로 제공하는 걸 이용했다.
참고) https://mybatis.github.io/spring/ko/batch.html




    



  




    
        
            
         
     
 





  
    
    




2015년 7월 1일 수요일

jfreeChart 에서 한글 깨질때 centos 폰트 설정

jfreeChart를 사용하는 중인데 tomcat위에서 돌리면 한글이 ㅁㅁㅁ 과 같이 나온다.

아래와 같이 한글 폰트를 os에 설치 한다. (물론 코드에서는 폰트 명을 지정해야 한다.)


yum install -y kde-i18n-Korean
yum install -y fonts-korean
fc-cache -fv

반영을 위하여 꼭 tomcat을 재시작 해야 한다.

2015년 6월 4일 목요일

OSX 10.10.3 homebrew 설치하기

터미널 열고


ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"



gimjonghuiui-MacBook-Pro:bin paper$ brew -v
Homebrew 0.9.5


출처: http://coolestguidesontheplanet.com/installing-homebrew-os-x-yosemite-10-10-package-manager-unix-apps/

2015년 4월 15일 수요일

하둡 스프링 연동 테스트2 - hadoop 2.6.x with spring 4.0 (MapReduce WordCount example)

context-hadoop.xml에 아래 내용 추가.


    fs.default.name=hdfs://localhost:9000










WordCount.java

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.StringTokenizer;

public class WordCount {
    private static final Logger logger = LoggerFactory.getLogger(WordCount.class);

    public static class TokenizerMapper
            extends Mapper<Object, Text, Text, IntWritable> {

        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();

        @Override
        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            logger.info("map key={}, value={}", key, value);

            StringTokenizer itr = new StringTokenizer(value.toString());
            while (itr.hasMoreTokens()) {
                word.set(itr.nextToken());
                context.write(word, one);
            }
        }
    }


    public static class IntSumReducer
            extends Reducer<Text, IntWritable, Text, IntWritable> {
        private IntWritable result = new IntWritable();

        @Override
        public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            logger.info("reduce key={}", key);

            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }
            result.set(sum);
            context.write(key, result);
        }
    }
}

Test.java

@Autowired
private org.apache.hadoop.conf.Configuration hdConf;

@Autowired
private JobRunner wordCountJobRunner;

@Before
public void beforeCopyFile() throws IOException {
    String file = "/Users/paper/Desktop/4/14/debug.2015-04-09.log";

    Path srcFilePath = new Path(file);
    Path dstFilePath = new Path("/input/debug.2015-04-09.log");

    FileSystem hdfs = FileSystem.get(dstFilePath.toUri(), hdConf);
    hdfs.copyFromLocalFile(false, true, srcFilePath, dstFilePath);

    hdfs.delete(new Path("/output/"), true);
}

@Test
public void testRunJob() throws Exception {
    wordCountJobRunner.call();
}


1. Before를 통하여 로컬에 있는 debug.log 파일을 hdfs에 카피 해놓는다.

2. Job을 실행한다.

3. 실행하면 debug.log 파일을 line단위로 읽어들이는걸 확인 할 수 있다. (WordCount$TokenizerMapper)

2015년 4월 12일 일요일

하둡 스프링 연동 테스트 - hadoop 2.6.x with spring 4.0

Hadoop 설치 및 설정은 아래와 같이 (osx 요세미티.)
https://hadoop.apache.org/releases.html#Download ( 2.6.x 버전 )

설치는 아래 블로그 보고 함
http://iamhereweare.blogspot.kr/2014/05/hadoop.html


- pom.xml 에 아래 dependency 추가.


  org.springframework.data
  spring-data-hadoop
  2.1.1.RELEASE



- context-hadoop.xml spring 설정에 파일 추가




    
        fs.default.name=hdfs://localhost:9000
    




아래와 같이 test코드 작성.
- HdTestServiceTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({
        "classpath:servlet-context.xml",
        "classpath:config/context-datasource.xml",
        "classpath:config/context-hadoop.xml"
})
public class HdTestServiceTest {
    private static final Logger logger = LoggerFactory.getLogger(HdTestService.class);

    @Autowired
    private org.apache.hadoop.conf.Configuration hdConf;

    @Test
    public void testDoTest() throws Exception {
        FileSystem hdfs = null;
        try {
            Path filePath = new Path("/tmp/test.txt");
            logger.info("filePath.uri={}", filePath.toUri());

            hdfs = FileSystem.get(filePath.toUri(), hdConf);

            if(hdfs.exists(filePath)) {
                logger.info("read file path={}", filePath);
                BufferedReader r = new BufferedReader(new InputStreamReader(hdfs.open(filePath), "utf-8"));
                String line = null;
                do {
                    line = r.readLine();
                    logger.info("  line={}", line);
                }
                while(line != null);
                r.close();

                // dfs.delete(filePath, true);
            } else {
                logger.info("create new file path={}", filePath);

                FSDataOutputStream out = hdfs.create(filePath, false);
                out.write("한글 생성 테스트".getBytes("utf-8"));
                out.flush();
                out.close();
            }
        }
        finally {
            IOUtils.closeQuietly(hdfs);
        }
    }
}

잘된다. 다만 아직 로컬에서 못벗어 났지만.. 벗어날 서버가 없어..
위 코드를 이용하면 파일 업로드 다운로드까지는 구현이 가능하겠다.