Spring整合Redis
Redis下载地址https://github.com/MicrosoftArchive/redis/releases
Redis五大类型:字符串(String)、哈希/散列/字典(Hash)、列表(List)、集合(Set)、有序集合(sorted set)五种
总括:
RedisTemplate redisTemplate.opsForValue();//操作字符串
RedisTemplate redisTemplate.opsForHash();//操作hash
RedisTemplate redisTemplate.opsForList();//操作list
RedisTemplate redisTemplate.opsForSet();//操作set
RedisTemplate redisTemplate.opsForZSet();//操作有序set
添加pom依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>1.5.0.RELEASE</version> </dependency>
Redis配置文件
spring.redis.host=localhost spring.redis.port=6379 #spring.redis.password=123456 #spring.redis.database=0 #spring.redis.pool.max-active=8 #spring.redis.pool.max-idle=8 #spring.redis.pool.max-wait=-1 #spring.redis.pool.min-idle=0 #spring.redis.timeout
添加Redis组件类RedisComponent 进行测试
@Component public class RedisComponent { @Autowired private StringRedisTemplate stringRedisTemplate; public void set(String key, String value) { ValueOperations<String, String> ops = this.stringRedisTemplate.opsForValue(); if (!this.stringRedisTemplate.hasKey(key)) { ops.set(key, value); System.out.println("set key success"); } else { // 存在则打印之前的value值 System.out.println("this key = " + ops.get(key)); } } public String get(String key) { return this.stringRedisTemplate.opsForValue().get(key); } public void del(String key) { this.stringRedisTemplate.delete(key); } }
在测试类中写入测试方法
@RunWith(SpringRunner.class) @SpringBootTest public class SpringBootDemo10ApplicationTests { @Autowired private RedisComponent redisComponent; @Test public void set() { redisComponent.set("redisTest", "hello world"); } @Test public void get() { System.out.println(redisComponent.get("redisTest")); } @Test public void del() { redisComponent.del("redisTest"); } }
- 启动上边下载好的Redis服务,在测试类进行增加、查看和删除操作,可以打开一个redis客户端页面,查看redis中的值