Posted
Filed under Linux
1. 톰켓 클러스터링 설정(config tomcat clustering)
[참고]
http://khaidoan.wikidot.com/tomcat-cluster-session-replication-without-multicasting
참고 하여 설정 함

ip 기반으로 서버 분산 처리 하는 경우
한 서버에 여러 개의 톰켓을 세팅 하는 방법은 검색하면 쉽게 해결 할 수 있음
본 글에서는 서로다른  ip주소 톰켓 을 세션 클러스터링 하기 위해서 ~


 <Manager className="org.apache.catalina.ha.session.DeltaManager"
             expireSessionsOnShutdown="false"
             notifyListenersOnReplication="true" />
바로 이부분이 아이피 기반 설정을 하기 위해서 필요함 Manager
톰켓 메니저의 자세한 설명은 tomcat.apache.org에 방문하면 확인 할 수 있음.

domain <--부분은 서로 일치 해야하며 , 
port <-- 서로다른 서버 임으로 4100포트로 통일

HOST 엘리먼트의 CONTEXT엘리먼트 PATH는 일치 해야함
session은 context기반으로 생성 됨으로 


붉은 색으로 표시 된 부분이 설정의 핵심임 UNIQUE아이디는 서로 달라야 함

LocalMember 은 자신의 서버 정보를 입력하면 되고

Member  은 원격지 서버의 정보를 입력 하면됨


마지막으로 

배포하는 어플리케이션의 web.xml에는 
<distributable />엘리먼트를 추가한다.


이렇게 하면 우선 서버 설정은 끝 
NGINX에서 로드벨런싱 세팅

server {
 
    listen       80;
    server_name  ssogate.fourfree.com;
    client_max_body_size 100M;
 
        location / {
                proxy_redirect     off;
                proxy_set_header   Host             $host;
                proxy_set_header   X-Real-IP        $remote_addr;
                proxy_set_header   X-Forwarded-For  $remote_addr;
                proxy_pass http://tomcat;
        }
 
        location ~^/ssogate2/* {
                proxy_redirect     off;
                proxy_set_header   Host             $host;
                proxy_set_header   X-Real-IP        $remote_addr;
                proxy_set_header   X-Forwarded-For  $remote_addr;
                proxy_pass http://tomcat2;
        }
}

ssogate.fourfree.com 서버의  nginx 설정 입니다.
ssogate.fourfree.com <-http://tomcat;
ssogate.fourfree.com/ssogate2/ <-- http://tomcat2;
으로 접근 하도록 설정 함 니다.

비록 서브 도메인이나 / 서로다른 도메인을 가지고 session을 공유 한것은 아니지만
사이트 내에서 덩치가 큰 서비스를 분리해 주기 위해서 tomcat 클러스터링을 이용했습니다.

소규모 사이트에서는 괜찮은 방법 같아 보입니다. sso 솔루션을 구매 하거나 josso를 이용해서 구축 해야 하지만 .
간단하게 session을 공유 할 수 있습니다. 
이방식으로 사이트 개발 후 서버에 배포 하려고 합니다 .~




server.xml1 설정
---------------------------------------------
 <Host name="ssogate.fourfree.com" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">
        <!--
                <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->
                <Alias>ssogate.fourfree.com</Alias>
                <Context path="/" docBase="/home/homepage/public_html" reloadable="true" workDir="/home/homepage/public_html/WEB-INF/classes" distributable="true"  className="org.apache.catalina.ha.context.ReplicatedContext"  sessionCookieDomain=".fourfree.com"  >
 
                <Manager className="org.apache.catalina.ha.session.DeltaManager"
             expireSessionsOnShutdown="false"
             notifyListenersOnReplication="true" />
 
 
                </Context>
 
                <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
           channelSendOptions="8">
 
    <Manager className="org.apache.catalina.ha.session.DeltaManager"
             expireSessionsOnShutdown="false"
             notifyListenersOnReplication="true" />
 
    <Channel className="org.apache.catalina.tribes.group.GroupChannel">
      <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
                address="1.220.141.43"
                port="4100"
                autoBind="100"
                selectorTimeout="5000"
                maxThreads="6" />
 
      <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
        <Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender" />
      </Sender>
 
      <Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector" />
 
      <Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor" />
 
      <Interceptor className="org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor" />
 
      <Interceptor className="org.apache.catalina.tribes.group.interceptors.StaticMembershipInterceptor">
 
        <LocalMember className="org.apache.catalina.tribes.membership.StaticMember"
                                                port="4100"
                                                securePort="-1"
                                                host="ssogate.fourfree.com"
                                                domain="tomcat-cluster"
                                                uniqueId="{15,1,2,3,4,5,6,7,8,9,10,11,12,13,14,0}"/>
 
        <Member className="org.apache.catalina.tribes.membership.StaticMember"
                host="ssogate2.fourfree.com"
                port="4100"
                securePort="-1"
                domain="tomcat-cluster"
                uniqueId="{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}" />


      </Interceptor>
    </Channel>
 
    <Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
           filter="" />
 
    <Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve" />
 
    <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener" />
  </Cluster>
</Host>



=============================================================================================================================
server.xml2 설정
<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
 
        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->
 
        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log" suffix=".txt"/>
 
      <!--
 <Context docBase="C:\Users\visualp\Desktop\java\sts\workspace-sts-3.6.2.RELEASE\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ROOT" path="" reloadable="false"/>
 -->
 <Alias>ssogate.fourfree.com</Alias>
 <Alias>ssogate2.fourfree.com</Alias>
 <Context docBase="C:\Users\visualp\Desktop\java\sts\workspace-sts-3.6.2.RELEASE\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\homepage" path="/" reloadable="true" source="org.eclipse.jst.jee.server:homepage" distributable="true"
className="org.apache.catalina.ha.context.ReplicatedContext"
sessionCookieDomain=".fourfree.com"
 >
 
<Manager 
className="org.apache.catalina.ha.session.DeltaManager" 
expireSessionsOnShutdown="false" 
notifyListenersOnReplication="true"
/>
 
 </Context>
 
 
<Cluster 
channelSendOptions="6" 
channelStartOptions="3" 
className="org.apache.catalina.ha.tcp.SimpleTcpCluster" defaultMode="true">
 
 
 
<Manager 
className="org.apache.catalina.ha.session.DeltaManager" 
expireSessionsOnShutdown="false" 
notifyListenersOnReplication="true"
/>
 
<Channel className="org.apache.catalina.tribes.group.GroupChannel">
<Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
<Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender" />
</Sender>
<Receiver 
address="61.32.203.30" 
autoBind="0" 
domain="tomcat-cluster"
className="org.apache.catalina.tribes.transport.nio.NioReceiver" 
maxThreads="6" 
port="4100" 
selectorTimeout="5000"
/>
<!-- <Interceptor className="com.dm.tomcat.interceptor.DisableMulticastInterceptor" /> -->
<Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpPingInterceptor" staticOnly="true"/>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector" />
<Interceptor className="org.apache.catalina.tribes.group.interceptors.StaticMembershipInterceptor">
 
<LocalMember className="org.apache.catalina.tribes.membership.StaticMember"
port="4100"
securePort="-1"
host="ssogate2.fourfree.com"
domain="tomcat-cluster"
uniqueId="{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}"/>
 
 
<Member className="org.apache.catalina.tribes.membership.StaticMember" 
port="4100" 
securePort="-1"
host="ssogate.fourfree.com" 
domain="tomcat-cluster"
uniqueId="{15,1,2,3,4,5,6,7,8,9,10,11,12,13,14,0}" />
/>
 
</Interceptor>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor" />
</Channel>
<Valve className="org.apache.catalina.ha.tcp.ReplicationValve" 
filter=".*\.gif;.*\.js;.*\.jpg;.*\.png;.*\.htm;.*\.html;.*\.css;.*\.txt;" 
/>
<ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener" />
</Cluster>
</Host>




2016/04/08 15:11 2016/04/08 15:11
Posted
Filed under Linux


형식

upstream 이름 {
    [ip_hash;]
    server host 주소:포트 [옵션];
    .....
}

옵션

옵션으로 올 수 있는 값은 아래와 같다.

  • ip_hash : 같은 방문자로부터 도착한 요청은 항상 같은 업스트림 서버가 처리 할 수 있게 한다.
  • weight=n : 업스트림 서버의 비중을 나타낸다. 이 값을 2로 설정하면 그렇지 않은 서버에 비해 두배 더 자주 선택된다.
  • max_fails=n : n으로 지정한 횟수만큼 실패가 일어나면 서버가 죽은 것으로 간주한다.
  • fail_timeout=n : max_fails가 지정된 상태에서 이 값이 설정만큼 서버가 응답하지 않으면 죽은 것으로 간주한다.
  • down : 해당 서버를 사용하지 않게 지정한다. ip_hash; 지시어가 설정된 상태에서만 유효하다.
  • backup : 모든 서버가 동작하지 않을 때 backup으로 표시된 서버가 사용되고 그 전까지는 사용되지 않는다.

예제

예를들면 아래와 같다.

upstream backend {
    ip_hash;
    server 192.168.125.142:9000 weight=3;
    server 192.168.125.143:9000;
    server 192.168.125.144:9000 max_fails=5 fail_timeout=30s;
    server unix:/var/run/php5-fpm.sock backup;
}

위의 설정을 풀어보면 아래와 같다.

같은 IP는 같은 업스트림 서버에 접속한다.
(ip_hash) 192.168.125.142 서버는 다른 서버 대비 3배 더 자주 사용된다.
192.168.125.144 서버는 30초 동안 응답하지 않는 상태가 5번 지속되면 죽은 것으로 간주하고 더 이상 요청을 보내지 않는다.
같은 호스트에 설치되서 소켓을 통해서 통신하는 FastCGI 에플리케이션은 백업용도이기 때문에 평소에는 사용하지 않다가 나머지 서버들이 불능상태가 되었을 때 자동으로 활성화된다.

2016/03/30 09:20 2016/03/30 09:20
Posted
Filed under JSP, JAVA

1. Servlet 3.1 deployment descriptor

Java EE 7 XML schema, namespace is http://xmlns.jcp.org/xml/ns/javaee/

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
</web-app>


2. Servlet 3.0 deployment descriptor

Java EE 6 XML schema, namespace is http://java.sun.com/xml/ns/javaee

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
</web-app>

3. Servlet 2.5 deployment descriptor

Java EE 5 XML schema, namespace is http://java.sun.com/xml/ns/javaee

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

</web-app

>


4. Servlet 2.4 deployment descriptor

J2EE 1.4 XML schema, namespace is http://java.sun.com/xml/ns/j2ee

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">

  <display-name>Servlet 2.4 Web Application</display-name>
</web-app>


5. Servlet 2.3 deployment descriptor

J2EE 1.3 DTDs schema. This web.xml file is too old, highly recommend you to upgrade it.

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Servlet 2.3 Web Application</display-name>
</web-app>

[원문]: http://www.mkyong.com/web-development/the-web-xml-deployment-descriptor-examples/

2016/03/23 15:54 2016/03/23 15:54
Posted
Filed under C#

[원문]
http://stackoverflow.com/questions/4161873/reduce-image-size-c-sharp

public static void SaveJpeg(string path, Image img, int quality)
        {
            if (quality < 0 || quality > 100)
                throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");

            // Encoder parameter for image quality
            EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            // JPEG image codec
            ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = qualityParam;
            img.Save(path, jpegCodec, encoderParams);
        }

        /// <summary>
        /// Returns the image codec with the given mime type
        /// </summary>
        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            // Get image codecs for all image formats
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            // Find the correct image codec
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];

            return null;
        }

2016/03/04 10:58 2016/03/04 10:58
Posted
Filed under nginx
다음과 같은 오류가 발생한다면, 버퍼 사이즈를 nginx에 설정 해줘야한다.

20xx/xx/xx xx:xx:xx [warn] ….an upstream response is buffered to a temporary file /var/cache/nginx/proxy_temp/xxxx while readi
ng upstream, client: xxx.xxx.xxx.xxx, server: aaa.aaaa.aaa.com, request: “GET /font/NanumGothic-Regular.woff HTTP/1.1”, upstream: “http:
//127.0.0.1:111/font/NanumGothic-ExtraBold.eot”,

http, location , server 중 아무데나 아래 값 추가 할 수 있음.
location에 추가함 .

proxy_buffering   on;
proxy_buffer_size    1024k;
proxy_buffers        1024   1024k;
client_body_buffer_size1024k;
proxy_busy_buffers_size1024k;
2016/02/24 09:54 2016/02/24 09:54
Posted
Filed under C#

[refference]http://stackoverflow.com/questions/3395381/c-sharp-converting-a-string-containing-a-floating-point-to-an-integer

var
a =(int)Convert.ToDouble("1.2");

Note if you're using comma as a number separator in your operating system, you have to use IFormatProvider:

var a =(int)Convert.ToDouble("1.2",CultureInfo.InvariantCulture.NumberFormat);

Another way to accomplish this task:

var a =int.Parse("1.2".Split('.')[0]);

2016/02/12 18:38 2016/02/12 18:38
Posted
Filed under C#
I found this solution to work for me when trying to access a file share on another computer.  It basically simulates doing a NET USE command where you can specify the credentials to use on the remote end.  The nice part is that you do not have to impersonate the user and it works across domains and workgroup computers.

First, declare these functions and types in your class.

using System.Reflection;
using System.Runtime.InteropServices;
using System.ComponentModel;

public class YourClass {
[DllImport("mpr.dll")]
private static extern int WNetAddConnection2A(ref NetResource pstNetRes, string psPassword, string psUsername, int piFlags);
[DllImport("mpr.dll")]
private static extern int WNetCancelConnection2A(string psName, int piFlags, int pfForce);

[StructLayout(LayoutKind.Sequential)]
private struct NetResource {
    public int iScope;
    public int iType;
    public int iDisplayType;
    public int iUsage;
    public string sLocalName;
    public string sRemoteName;
    public string sComment;
    public string sProvider;
}

private const int RESOURCETYPE_DISK = 0x1;

Then, add these two methods.
   
    private void LoginToShare(string serverName, string shareName, string user, string password) {
        string destinationDirectory = string.Format(@"\\{0}\{1}", serverName, shareName);

        NetResource nr = new NetResource();
        nr.iScope = 2;
        nr.iType = RESOURCETYPE_DISK;
        nr.iDisplayType = 3;
        nr.iUsage = 1;
        nr.sRemoteName = destinationDirectory;
        nr.sLocalName = null;

        int flags = 0;
        int rc = WNetAddConnection2A(ref nr, password, user, flags);

        if (rc != 0) throw new Win32Exception(rc);
    }

    private void LogoutFromShare(string serverName, string shareName) {
        string destinationDirectory = string.Format(@"\\{0}\{1}", serverName, shareName);
        int flags = 0;
        int rc = WNetCancelConnection2A(destinationDirectory, flags, Convert.ToInt32(false));
    }


In your code, call the LoginToShare with the server, share, user, and password needed.  Then simply use the standard \\server\share\path conventions for accessing files on remote computers.  Call the LogoutFromShare when you're done.

http://www.nullskull.com/q/10116970/accessing-shared-folder-on-a-network-using-c-code.aspx

2016/01/26 10:05 2016/01/26 10:05
Posted
Filed under spring framework
[출처] :http://stackoverflow.com/questions/16712462/many-commandname-for-one-form-in-spring-mvc
public
classCombinedCommand(){Activity activity;Etabl etabl;//Getter and setter}

jsp:

<form:form
  action="${pageContext.request.contextPath}/ajouter_activite"
  method="post" commandName="combinedCommand"">...<form:input type="text"path="activity.x"/>...<form:input type="text"path="etabl.y"/>...</form:form>
2015/12/14 11:24 2015/12/14 11:24
Posted
Filed under JSP, JAVA
[원문]http://sexy.pe.kr/tc/764


자바 Math 클래스에서 실수값 반올림이나 올림, 버림, 절대값을 구해주는 메서드가 있다.

반올림
static long Math.round(double a)
static int Math.round(float a)
예) System.out.println(Math.round(100.56)); //결과: 101


올림
static double ceil(double a)

예) System.out.println(Math.ceil(100.56)); //결과: 101.0


버림
static double floor(double a)

예) System.out.println(Math.floor(100.56)); //결과: 100.0


절대값
static double abs(double a)
static float abs(float a)
static int abs(int a)
static long abs(long a)

예) System.out.println(Math.abs(-100.56)); //결과: 100.56


참고로 소수 둘째자리에서 반올림을 하고 싶다고 하면 아래와 같이 응용한다.

double a = 100.22516;
double b = Math.round(a*100d) / 100d;
System.out.println(b); //결과: 100.23

원리는 차근차근 따라해 보면 쉽다.
일반 round() 메서드는 소수첫째자리에서 반올림 되기때문에 내가 반올림 하고자하는 자리수가 첫번째 소수점자리가 되도록 10 제곱을 곱해준다.
즉, 소수 2번째 자리까지 구하기 때문에 a에 10^2 하게되면 10022.516이 된다.
여기에서 반올림 한후 다시 나눈만큼 곱해주면 원래 소수 자리로 복원되게 된다.

다른 방법으로는 서식출력이 가능한 표준출력 메서드를 이용한 방법이다.
double a = 100.22516;
System.out.printf("%.2f",a); //결과 100.23

소수 둘째자리 실수로 반올림하여 출력하는 메서드이다.


간단한 내용이면서도 자주 활용되는 메서드에 대해 정리해보았습니다.
2015/12/03 16:14 2015/12/03 16:14
Posted
Filed under JSP, JAVA
[원문]http://hellogk.tistory.com/85

/**
 * Pathvariable example
 * @return
 */
@RequestMapping("/page/{var}")
public String page(@PathVariable String var){
    String returnUrl = "";
    if(var.equals("one")) {
        returnUrl = "page1";
    } else if(var.equals("two")) {
        returnUrl = "page2";
    }
    return returnUrl;
}
2015/11/18 17:46 2015/11/18 17:46