Redisとspring-boot連携

Redisとは
インメモリのkey-valueストア
メモリ上にデータを格納するので,非常に高速にデータの書き込み・読み込みを行うことができる。
キャッシュの保存とかセッション管理とかに使えるかも。

Redisインストール
epelリポジトリに含まれていたからyumでインストールした

yum install redis

インストールできなかったらepelリポジトリ追加して試す

yum install epel-release
yum --enablerepo=epel install redis


redisサーバの起動

redis-server

redisクライアントの起動

redis-cli

spring boot連携
・pom.xmlに以下を追加

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-redis</artifactId>
</dependency>

・application.propertiesにredisの接続情報を記入

spring.redis.host=localhost
#spring.redis.password=secret
spring.redis.port=6379

・Redisに値をset, getする

@Controller
public class SampleController {

	@Autowired
	private HelloWorldService helloWorldService;
	
	@Autowired
	private StringRedisTemplate template;

	@RequestMapping("/")
	@ResponseBody
	public String helloWorld(HttpServletRequest request) {
		ValueOperations<String, String> ops = this.template.opsForValue();
		String key = "spring.boot.redis.test";
		if (!this.template.hasKey(key)) {
			ops.set(key, "foo");
		}
		System.out.println("Found key " + key + ", value=" + ops.get(key));
		
		return this.helloWorldService.getHelloMessage();
	}
}

Redisに保存されているかは以下のコマンドで確認できる。

redis-cli
127.0.0.1:6379> KEYS *
1) "spring.boot.redis.test"
127.0.0.1:6379> get spring.boot.redis.test
"foo"