spring과 redis연동

Spring 2014. 9. 18. 09:26

SDR(spring-data-redis) 와 jedis커넥션을 이용한 spring을 이용한 redis 연동.


spring에서 redis를 연결하기 위한 기본적인 방법을 커넥션 위주로 설명.

실제로는 redis에 저장할 데이타 class를 별도로 만들어 serialize기능을 이용해 {key,class}형태로 저장하는 방식이 바람직하지만, 여기서는 이 부분은 생략하고 기본적인 연결과정만 설명한다. 


1. pom.xml 수정   (SDR , common-pool,  jedis를 추가)


<dependency>

<groupId>org.springframework.data</groupId>

<artifactId>spring-data-redis</artifactId>

<version>1.4.0.RELEASE</version>

</dependency>

<dependency>

<groupId>commons-pool</groupId>

<artifactId>commons-pool</artifactId>

<version>1.6</version>

</dependency>

<dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-pool2</artifactId>

<version>2.0</version>

</dependency>

<dependency>

<groupId>redis.clients</groupId>

<artifactId>jedis</artifactId>

<version>2.5.1</version>

<type>jar</type>

<scope>compile</scope>

</dependency>






2. application-config.xml 수정


2.1 네임스페이스에  xmlns:p 추가.

2.2  jedisConnnection, Serializer, redisTemplate 추가.


<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:p="http://www.springframework.org/schema/p"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


    <!-- Uncomment and add your base-package here:-->

    <context:component-scan base-package="my"/>


<bean id="jedisConnFactory"

    class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"

    p:use-pool="true" p:host-name="127.0.0.1" p:port="6379" />


<bean id="stringRedisSerializer"

    class="org.springframework.data.redis.serializer.StringRedisSerializer"/>


<!-- redis template definition -->

<bean id="redisTemplate"

class="org.springframework.data.redis.core.RedisTemplate"

p:connection-factory-ref="jedisConnFactory"

p:keySerializer-ref="stringRedisSerializer"

p:hashKeySerializer-ref="stringRedisSerializer"

p:valueSerializer-ref="stringRedisSerializer"/>


</beans>



  이 중에서 serializer는 추가하지 않아도 동작은 잘 되지만, 

 기본 serializer로 동작하게 되면 redis에 데이타가 들어갈 때, 앞 부분에 xac xed x00 x05t x00 등의 character가 몇개 들어가게 된다.

(이런 이상한 캐릭터들은 standard serializer에서 사용하는 class정보이다.)




3. JAVA Service 코드


 @Service

public class RedisService implements IRedisService{


@Autowired

private RedisTemplate<String,String> redisTemplate;


public Set<String> keysAll() {


//값을 넣고 싶을 땐, 이렇게..

//redisTemplate.opsForValue().set("abcKey", "valueABC");


return redisTemplate.keys("*");

}



}     


Posted by yongary
,