Redis 서버 준비

Spring에서 Redis를 사용하려면 먼저 Redis가 설치되어 있어야 합니다. ( 다운 )


다운로드를 하면 위와 같은 파일들이 있는데,

redis-server.exe 파일을 실행하면 Redis 서버가 실행되며,

redis-cli.exe 파일을 실행하면 명령어를 보낼 수 있습니다.


간단하게 테스트 해보기 위해 redis-cli에서 아래의 명령을 입력해보세요.

set example spring-redis  :  key value 쌍을 추가

keys *                :  모든 key 값을 확인

get example    : 특정 key의 value를 확인




이제 본격적으로 Spring에서 Redis를 사용하는 방법을 알아보겠습니다.


준비 작업

프로젝트 구조는 다음과 같습니다.


1) pom.xml

<dependencies>

        <dependency>

               <groupId>org.springframework</groupId>

               <artifactId>spring-context</artifactId>

               <version>${org.springframework-version}</version>

        </dependency>

        <!-- Spring Web -->

        <dependency>

               <groupId>org.springframework</groupId>

               <artifactId>spring-web</artifactId>

               <version>${org.springframework-version}</version>

        </dependency>


        <!-- Spring MVC -->

        <dependency>

               <groupId>org.springframework</groupId>

               <artifactId>spring-webmvc</artifactId>

               <version>${org.springframework-version}</version>

        </dependency>


        <!-- redis -->

        <dependency>

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

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

               <version>1.5.0.RELEASE</version>

        </dependency>

        <dependency>

               <groupId>redis.clients</groupId>

               <artifactId>jedis</artifactId>

               <version>2.8.0</version>

        </dependency>

        <dependency>

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

               <artifactId>commons-pool2</artifactId>

               <version>2.4.2</version>

        </dependency>

</dependencies>




2) 

jedis를 사용하기 위해서는 실행되고 있는 Redis server와 연결돼야 합니다.

JedisConnectionFactory 인스턴스를 생성을 통해 Redis와 연결할 수 있습니다.


먼저 com.victolee.redis 패키지를 생성하여, SpringRedisConfig.java 클래스를 생성합니다.

com.victolee.redis.SpringRedisConfig.java

@Configuration
public class SpringRedisConfig {
	@Bean
	public JedisConnectionFactory connectionFactory() {
		JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
		connectionFactory.setHostName("localhost");
		connectionFactory.setPort(6379);
		return connectionFactory;
	}
}

Redis-server의 포트는 기본 값으로 6379를 사용하고 있습니다.



스프링은 RedisTemplate 클래스를 제공하는데, 이는 Redis 데이터에 쉽게 접근하기 위한 코드를 제공합니다.

Template를 사용하기 위해 RedisTemplate Bean을 추가합니다.

com.victolee.redis.SpringRedisConfig.java

@Bean
public RedisTemplate<String, Object> redisTemplate(){
	RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
	redisTemplate.setConnectionFactory(connectionFactory());
	redisTemplate.setKeySerializer(new StringRedisSerializer());
	return redisTemplate;
}

RedisTemplate을 JedisConnectionFactory와 연결 하고,

주어진 객체와 Redis 데이터간의 serialization / deserialization을 자동으로 수행하는 StringRedisSerializer를 설정합니다.




3)

다음으로 Redis Value Operation에 사용 할 VO 객체인 Employee 클래스를 생성합니다.

com.victolee.redis.vo.Employee

public class Employee implements Serializable{
	private static final long serialVersionUID = 1L;
	private String id;
	private String name;
	private Integer age;
	
	public Employee() {}
	
	public Employee(String id, String name) {
		this.id = id;
		this.name = name;
	}

	// getter, setter 생략

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
}





이상으로 준비 작업은 모두 마쳤습니다.

Redis에는 다양한 Operation을 지원하는데, 

이제 Redis가 지원하는 몇 가지 Operation을 사용해보도록 하겠습니다.


Redis Operation - set , get , value

com.victolee.service.SpringRedisExample.java

@Service
public class SpringRedisExample {
	public void exam() {
		ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(SpringRedisConfig.class);
		try {
			@SuppressWarnings("unchecked")
			RedisTemplate<String, Object> redisTemplate = (RedisTemplate<String, Object>)ctx.getBean("redisTemplate");
			// value operation
			ValueOperations<String, Object> values = redisTemplate.opsForValue();
			
			// set
			values.set("victolee", new Employee("01", "victolee"));
			
			// get
			System.out.println("Employee added : " + values.get("victolee"));
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		finally {
			ctx.close();
		}
		
	}
}

큰 의미는 없지만, 3-Layer-Architecture를 따르기 위해 예제 메서드를 Service 계층에 두었습니다.


이제 테스트를 위해 컨트롤러에서 위의 메서드를 호출하도록 코드를 작성한 후 서버를 실행하여 브라우저에서 접근해보세요.


콘솔에는 위와 같이 출력되는 것을 확인할 수 있습니다.

실제로 Redis Server에 데이터가 들어갔는지 확인하기 위해 redis-cli.exe에서 keys * 명령어를 작성합니다.


Redis Sever에도 데이터가 잘 들어갔네요.





Redis Operation - Hash

다음은 Hash Operaion에 대해 알아보겠습니다.

@Service
public class SpringRedisExample {
	public void exam() {
		ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(SpringRedisConfig.class);
		try {
			@SuppressWarnings("unchecked")
			RedisTemplate<String, Object> redisTemplate = (RedisTemplate<String, Object>)ctx.getBean("redisTemplate");
			
			Map<String, String> empBobMap = new HashMap<>();
			empBobMap.put("name", "Bob");
			empBobMap.put("age", "26");
			empBobMap.put("id", "02");
			
			Map<String, String> empJohnMap = new HashMap<>();
			empJohnMap.put("name", "John");
			empJohnMap.put("age", "16");
			empJohnMap.put("id", "03");
			
			// Hash Operation
			HashOperations<String, String, String> hash = redisTemplate.opsForHash();
			String empBobKey = "emp:Bob";
			String empJohnKey = "emp:John";
			
			hash.putAll(empBobKey, empBobMap);
			hash.putAll(empJohnKey, empJohnMap);
			
			System.out.println("Get emp Bob : " + hash.entries(empBobKey));
			System.out.println("Get emp John : " + hash.entries(empJohnKey));
			
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		finally {
			ctx.close();
		}
		
	}
}






String Redis Template

다음으로는 RedisTemplate 외에 또 다른 Template인 StringRedisTemplate에 대해 알아보겠습니다.

StringRedisTemplate은 긴 문자열을 다룰 때 사용하는 것이 좋습니다.

간혹 문자열이 깨지는 경우가 발생하는데, 이 경우에도 StringRedisTemplate을 사용하면 해결이 되는 경우가 있었습니다.


StringRedisTemplate을 사용하기 위해서는 SpringRedisConfig에 Bean을 추가하면 됩니다.

com.victolee.redis.SpringRedisConfig.java
@Bean
public StringRedisTemplate strRedisTemplate() {
	StringRedisTemplate redisTemplate = new StringRedisTemplate();
	redisTemplate.setConnectionFactory(connectionFactory());
	return redisTemplate;
}

이렇게 Bean을 등록하기만 하면, StringRedisTemplate 사용이 가능합니다.

앞에서 살펴 본 두 Operation에서 redisTemplate의 타입을 RedisTemplate 대신 StringRedisTemplate으로 바꾸기만 하면 같은 결과를 얻을 수 있습니다.




이상으로 Spring에서 Redis를 사용하기 위한 환경 설정 및 Redis에서 지원하는 몇 가지 Operation에 대해 알아보았습니다.


[ 참고 자료 ]

http://arahansa.github.io/docs_spring/redis.html

https://examples.javacodegeeks.com/enterprise-java/spring/spring-data-redis-example-2/