- 添加依赖
<!-- redis数据库 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
2.配置application.yml
#redis配置 spring: redis: #redis数据库索引(默认为0) database : 0 #redis服务器地址 host: localhost #redis服务器连接端口 port: 6379 #redis连接密码 password: #redis连接池设置 pool: #最大空闲连接 max-idle : 100 #最小空闲连接 min-idle : 1 #最大连接数(负数表示没有限制) max-active : 1000 #最大阻塞等待时间(负数表示没有限制) max-wait : -1 #连接超时时间(毫秒) timeout : 0
如果配置了其他spring开头的设置,会报错
检查yml的配置,发现datasource的key与redis的同为spring
所以把二者合并,将redis的配置移到spring下,application.yml的内容如下
server: port: 8080 spring: datasource: name: test url: jdbc:mysql://192.168.20.30:3607/us_sys username: root password: root # 使用druid数据源 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver filters: stat maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20 #redis配置 redis: #redis数据库索引(默认为0) database : 0 #redis服务器地址 host: localhost #redis服务器连接端口 port: 6379 #redis连接密码 password: #redis连接池设置 pool: #最大空闲连接 max-idle : 100 #最小空闲连接 min-idle : 1 #最大连接数(负数表示没有限制) max-active : 1000 #最大阻塞等待时间(负数表示没有限制) max-wait : -1 #连接超时时间(毫秒) timeout : 0 mybatis: mapper-locations: classpath:mapping/*.xml type-aliases-package: com.lvpeilei.model
3.编写测试类
添加测试工具的maven依赖
1 <!-- 测试 --> 2 <dependency> 3 <groupId>junit</groupId> 4 <artifactId>junit</artifactId> 5 <scope>test</scope> 6 </dependency> 7 <dependency> 8 <groupId>com.fasterxml.jackson.jaxrs</groupId> 9 <artifactId>jackson-jaxrs-xml-provider</artifactId> 10 <scope>test</scope> 11 </dependency> 12 <dependency> 13 <groupId>org.springframework.boot</groupId> 14 <artifactId>spring-boot-starter-test</artifactId> 15 <scope>test</scope> 16 </dependency>
编写测试类
1 @RunWith(SpringJUnit4ClassRunner.class) 2 @SpringBootTest(classes = Application.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 3 @EnableAutoConfiguration 4 public class ApplicationRedisTest { 5 6 @Autowired 7 private StringRedisTemplate stringRedisTemplate; 8 9 @Test 10 public void test() throws Exception{ 11 //保存字符串 12 stringRedisTemplate.opsForValue().set("aaa","111"); 13 Assert.assertEquals("111",stringRedisTemplate.opsForValue().get("aaa")); 14 } 15 }