Development/Spring

Spring Framework 과 Redis 연동

南山 2017. 8. 7. 11:10

 

Spring Framework 과 Redis 연동하기.

 

 

NoSQL 이란 Big data 를 처리하기 위한 분산 데이터 저장소를 통칭하며, 

Redis 는 key-value 형태의 데이터 저장소를 지원하는 NoSQL 의 일종이다.

CAP(Consistency, Availability, Partition Tolerence) 특징중에서 CP 에 더 가까운 고속의 읽기/쓰기에 최적화 된 모델이다.

 






개발환경

JDK 1.8Spring Framework 4.3.7 RELEASEMAVEN 3Windows 10

 

 

Windows 용 Server 구동

 

Redis 는 Linux, Unix, MacOS 는 지원하지만 Windows 는 정식으로 지원하지 않는다. Windows 용 서버는 개발/스터디 용도로만 사용해야 한다.

 

....

C:\dev\redis-2.4.5-win32-win64\64bit>redis-server[8804] 08 Aug 14:18:28 # Warning: no config file specified, using the default config. In order to specify a config file use 'redis-server /path/to/redis.conf'[8804] 08 Aug 14:18:28 * Server started, Redis version 2.4.5[8804] 08 Aug 14:18:28 # Open data file dump.rdb: No such file or directory[8804] 08 Aug 14:18:28 * The server is now ready to accept connections on port 6379[8804] 08 Aug 14:18:29 - 0 clients connected (0 slaves), 1179896 bytes in use[8804] 08 Aug 14:18:34 - 0 clients connected (0 slaves), 1179896 bytes in use[8804] 08 Aug 14:18:39 - 0 clients connected (0 slaves), 1179896 bytes in use[8804] 08 Aug 14:18:44 - 0 clients connected (0 slaves), 1179896 bytes in use[8804] 08 Aug 14:18:49 - 0 clients connected (0 slaves), 1179896 bytes in use[8804] 08 Aug 14:18:54 - 0 clients connected (0 slaves), 1179896 bytes in use[8804] 08 Aug 14:18:59 - 0 clients connected (0 slaves), 1179896 bytes in use[8804] 08 Aug 14:19:04 - 0 clients connected (0 slaves), 1179896 bytes in use[8804] 08 Aug 14:19:09 - 0 clients connected (0 slaves), 1179896 bytes in use[8804] 08 Aug 14:19:14 - 0 clients connected (0 slaves), 1179896 bytes in use[8804] 08 Aug 14:19:19 - 0 clients connected (0 slaves), 1179896 bytes in use[8804] 08 Aug 14:19:24 - 0 clients connected (0 slaves), 1179896 bytes in use[8804] 08 Aug 14:19:29 - 0 clients connected (0 slaves), 1179896 bytes in use[8804] 08 Aug 14:19:34 - 0 clients connected (0 slaves), 1179896 bytes in use

 

[8804] 08 Aug 14:19:39 - 0 clients connected (0 slaves), 1179896 bytes in use
....

 

서버를 구동하면 설정 정보가 출력되고 5초 간격으로 Redis Server 의 상태 로그가 출력된다.

 

 

 

 

 

Client 구현(Spring Framework 통합)

 

pom.xml

....

<dependency>            <groupId>redis.clients</groupId>            <artifactId>jedis</artifactId>            <version>2.9.0</version>        </dependency>

 

        <dependency>            <groupId>org.springframework.data</groupId>            <artifactId>spring-data-redis</artifactId>            <version>1.8.6.RELEASE</version>

 

        </dependency>
 

....

 

필요한 dependency 를 정의해준다.

 

 

 

 

spring-context.xml

....

    <!-- Redis -->    <bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"          p:usePool="true"          p:hostName="localhost"          p:port="6379"    />
    <!-- Object for Redis -->    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"          p:connectionFactory-ref="jedisConnFactory"

 

    />
 

....

 

 

 

 

 

UserDto.java

....

public class UserDto implements Serializable {

 

    private static final long serialVersionUID = 6693831067440491652L;

....

 

 

 

 

RedisServiceImpl.java

....

@Autowired

 

    private RedisTemplate<String, Object> redisTemplate;
....

@Service

public class RedisServiceImpl implements RedisService {

 

    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    private String TAG = this.getClass().getName();

 

    @Autowired

    private RedisTemplate<String, Object> redisTemplate;

 

    /**

     * Redis 에 사용자 정보를 등록한다.

     *

     * @param userDto

     */

    public void setUserInformation(UserDto userDto) {

        logger.debug("> setUserInformation", TAG);

 

        String key = "userDto:" + userDto.getUserId();

 

        Map<String, Object> mapUserDto = new HashMap<String, Object>();

        mapUserDto.put("userId", userDto.getUserId());

        mapUserDto.put("userPassword", userDto.getUserPassword());

        mapUserDto.put("phoneNumber", userDto.getPhoneNumber());

 

        redisTemplate.opsForHash().putAll(key, mapUserDto);

    }

 

    /**

     * Redis 에서 사용자 정보를 가져온다.

     *

     * @param userDto

     * @return

     */

    public UserDto getUserInformation(UserDto userDto) {

        logger.debug("> getUserInformation", TAG);

 

        String key = "userDto:" + userDto.getUserId();

 

        UserDto result = new UserDto();

        result.setUserId((String)redisTemplate.opsForHash().get(key, "userId"));

        result.setUserPassword((String)redisTemplate.opsForHash().get(key, "userPassword"));

        result.setPhoneNumber((String)redisTemplate.opsForHash().get(key, "phoneNumber"));

 

        logger.debug("> userId       : {}", result.getUserId(), TAG);

        logger.debug("> userPassword : {}", result.getUserPassword(), TAG);

        logger.debug("> phoneNumber  : {}", result.getPhoneNumber(), TAG);

 

        return result;

    }

}

 

 

Redis 는 key-value 의 형태를 기본으로 사용하지만 application 에서 사용하는 domain object 를 표현하기 위해서는 field, value 의 맵으로 표현하는 hash 가 가장 최적의 유형이다.

 

UserDto domain object 를 예로 들면, key : field : value 를 userDto : userId : cale9797 의 유형으로 표현할 수 있다.