springboot整合redis
概述
这篇文章主要是根据springboot官方给出的demo做的一个springboot整合redis的一个入门级别的博客。
springboot整合redis需要了解的知识点:
1. springboot的基本了解,包括常用注解、依赖、配置文件
2. redis的基本了解,最起码需要知道redis的如何安装及安全设置
3. spring data redis的基本了解,springboot整合redis实际上是对此做了一些封装。
步骤
- 依赖添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
</dependency>
- 配置文件application.yml编写
spring:
redis:
host: 192.168.44.129
password: admin
session:
store-type: none
注意:redis安装成功后,默认密码为空。所以需要先配置一个redis的密码,否则可能会出现问题以下问题:http://blog.csdn.net/mynameissls/article/details/73130989
- 测试启动类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
private StringRedisTemplate template;
@Override
public void run(String... args) throws Exception {
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));
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
运行完测试启动类后,可以去redis的服务器上查看是否存在key=spring.boot.redis.test的一个数据,如下:
[root@localhost src]# ./redis-cli
127.0.0.1:6379> auth admin
OK
127.0.0.1:6379> get spring.boot.redis.test
"foo"
127.0.0.1:6379>
参考链接:https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples
源代码链接:https://github.com/myNameIssls/springboot-study