티스토리 뷰

Database/redis

Redis - Spring 연동

chan20 2020. 7. 20. 14:44

검색을 많이 해봣지만 Spring 과 Redis랑 연동한것은 별로 없었다. 

Spring-Boot로 진행 한 것들이 많았는데 이런 부분들이 많이 힘들었다.

RedisConfig.java


@Configuration
public class SpringRedisConfig {
	@Bean
	public JedisConnectionFactory connectionFactory() {
		JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
		connectionFactory.setHostName("localhost");
		connectionFactory.setPort(6379);
		return connectionFactory;
	}
	
	@Bean
	public RedisTemplate<String, Object> redisTemplate(){
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
		redisTemplate.setConnectionFactory(connectionFactory());
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		return redisTemplate;
	}
	
	@Bean
	public StringRedisTemplate strRedisTemplate() {
		StringRedisTemplate redisTemplate = new StringRedisTemplate();
		redisTemplate.setConnectionFactory(connectionFactory());
		return redisTemplate;
	}
}

일단 Redis를 연결하기위해 Jedis로 연결을 해야한다고 한다. localhost 자기 IP주소와 port번호 넣어서  Bean에 등록해준다

또 Bean에다가 RedisTemplate를 등록해서 Autowired로 보낼까 생각했다.

RedisPrectice.java

@Service
public class SpringRedisExample {
	static int TIMES = 10;
	
	@Resource(name= "RedisTemplate")
	ValueOperations<String, Object> valu; 
	
	public void exam() {
		ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(SpringRedisConfig.class);
		try {
			@SuppressWarnings("unchecked")
			RedisTemplate<String, Object> redisTemplate = (RedisTemplate<String, Object>)ctx.getBean("redisTemplate");

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

			redisTemplate.setKeySerializer(new StringRedisSerializer());
			redisTemplate.setValueSerializer(new StringRedisSerializer());
			Map<String, String> aMap = new HashMap<String, String>();
			aMap.put("name", "chan");
			aMap.put("age", "25");
			aMap.put("id", "hello");
			
			Map<String, String> bMap = new HashMap<String ,String>();
			bMap.put("name", "kang");
			bMap.put("age", "24");
			bMap.put("id", "world");
			
			// Hash Operation
			HashOperations<String, String, String> hash = redisTemplate.opsForHash();
			
			hash.putAll("akey", aMap);
			hash.putAll("bkey", bMap);
			
			System.out.println("Get emp Bob : " + hash.entries("akey"));
			System.out.println("Get emp John : " + hash.entries("bkey"));
			
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		finally {
			ctx.close();
		}
		
	}
	public void string(String no , String name, String age ) {
		ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(SpringRedisConfig.class);
		try {
			@SuppressWarnings("unchecked")
			RedisTemplate<String, Object> redisTemplate = (RedisTemplate<String, Object>)ctx.getBean("redisTemplate");

			redisTemplate.setKeySerializer(new StringRedisSerializer());
			redisTemplate.setValueSerializer(new StringRedisSerializer());
			Map<String, String> people = new HashMap<String, String>();
			people.put("name", name);
			people.put("age", age);
			
			HashOperations<String, String, String> hash = redisTemplate.opsForHash();
			String no1 = no;
			
			
			hash.putAll(no1, people);
			
			System.out.println(no+ ": " + hash.entries(no1));
			
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		finally {
			ctx.close();
		}
		
	}
	public void list(String name, String value) {
		ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(SpringRedisConfig.class);
		try {
			@SuppressWarnings("unchecked")
			RedisTemplate<String, Object> redisTemplate = (RedisTemplate<String, Object>)ctx.getBean("redisTemplate");

			redisTemplate.setKeySerializer(new StringRedisSerializer());
			
			ListOperations<String, Object> lists = redisTemplate.opsForList();
			Instant instant = Instant.now();
			long times = instant.toEpochMilli();
			
			lists.leftPush(name, value);
			System.out.println(name+ ": " + lists.getOperations());
			
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		finally {
			ctx.close();
		}
	}
	public void sort(String name, String value) {
		ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(SpringRedisConfig.class);
		try {
			@SuppressWarnings("unchecked")
			RedisTemplate<String, Object> redisTemplate = (RedisTemplate<String, Object>)ctx.getBean("redisTemplate");

			redisTemplate.setKeySerializer(new StringRedisSerializer());
			
			ZSetOperations<String, Object> lists = redisTemplate.opsForZSet();
			Instant instant = Instant.now();
			long times = instant.toEpochMilli();
			
			lists.add(name, value, times);
			
			System.out.println(name+ ": " + lists.toString());
			
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		finally {
			ctx.close();
		}
	}

여기서 각종 Operations에 @Autowired와 @resource를 사용하여 주입 해보고 싶었지만 주입하면

NullPointerException 오류가 생긴다. 아무래도 주입이 안된 것 같다. (Spring Boot에서만 되는건가 ..?)

직접 Bean 생성 말고 함수 안에 어노테이션 말고 getBean을 이용하여 직접 적었더니 되긴 되는 것 같다.

@SuppressWarnings("unchecked") 이것은 RedisTemplate을 생성하면 붙는데 검증되지 않는 연산자를 경고 제외할 때 쓰인다

Controller.java

@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	
	@GetMapping(value = "/")
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		SpringRedisExample ex = new SpringRedisExample();
		ex.exam();
		
		return "home";
	}
	
	
	@GetMapping(value = "/{name}/{age}")
	public String home2(@PathVariable String name, @PathVariable String age) {
		
		SpringRedisExample ex = new SpringRedisExample();
		ex.string("people", name, age);
		
		return "home";
	}
	@GetMapping(value = "/{name}/{value}/{value2}")
	public String home3(@PathVariable String name, @PathVariable String value, @PathVariable String value2) {
		
		SpringRedisExample ex = new SpringRedisExample();
		ex.list(name, value);
		ex.sort(name, value2);
		return "home";
	}
	@GetMapping(value = "/delete/list/{number}")
	public String home4(@PathVariable String number) {
		
		if(number.equals("1")) {
			
		}
		else if(number.equals("2")) {
			
		}
		return "home";
	}
	
}

 컨트롤러 부분이다. 그냥 url 로 PathVariable로 받아와서 redis에 값을 넣기 위해 사용 했다.

 home3 부분보면 list와 sort가 같은 key값을 받고 있는데 이러면 충돌하여 오류가 생긴다. 

redis 연습한 코드

https://github.com/Lee-kangchan/Redis_Prectice/

 

Lee-kangchan/Redis_Prectice

Redis, Spring 연동 및 연습. Contribute to Lee-kangchan/Redis_Prectice development by creating an account on GitHub.

github.com

 

'Database > redis' 카테고리의 다른 글

redis 자료구조 및 명령어  (0) 2020.07.20
레디스(Redis) 란?  (0) 2020.07.16
NOSQL  (0) 2020.07.16