步骤:
- 引入pom依赖
- 配置文件
- 注解@EnableCaching
- 开始使用
下面开始实现
引入pom
使用的是IDEA,新建一个全新的工程:
直接在创建的时候引入:
在springboot2之后,redis默认集成的是lettuce,如果要使用jedis,需要使用第二个xml配置
第一种:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
第二种, 修改redis的引入方式,然后修改一些配置,稍后列出:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<!-- 1.5的版本默认采用的连接池技术是jedis 2.0以上版本默认连接池是lettuce, 在这里采用jedis,所以需要排除lettuce的jar -->
<exclusions>
<exclusion>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</exclusion>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 添加jedis客户端 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!--spring2.0集成redis所需common-pool2-->
<!-- 必须加上,jedis依赖此 -->
<!-- spring boot 2.0 的操作手册有标注 大家可以去看看 地址是:https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>RELEASE</version>
</dependency>
配置文件【先使用默认的配置】
spring:
redis:
# Redis服务器地址
host: 127.0.0.1
# Redis数据库索引(默认为0)
database: 0
# Redis服务器连接端口
port: 6379
password: 这里是redis的密码
#连接超时时间(毫秒)
timeout: 3600
注解@EnableCaching
要使用redis,直接在启动类上加注解:
@EnableCaching
@SpringBootApplication
public class RedisApplication {
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}
使用
先来一个controller,然后来一个service。注意用到了web,引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
启动类上加注解。
@EnableCaching
@SpringBootApplication
public class RedisApplication {
public static void main(String[] args