<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
#redis配置 #Redis服务器地址 spring.redis.host=127.0.0.1 #Redis服务器连接端口 spring.redis.port=6379 #Redis数据库索引(默认为0) spring.redis.database=0 #连接池最大连接数(使用负值表示没有限制) spring.redis.jedis.pool.max-active=50 #连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.jedis.pool.max-wait=3000 #连接池中的最大空闲连接 spring.redis.jedis.pool.max-idle=20 #连接池中的最小空闲连接 spring.redis.jedis.pool.min-idle=2 #连接超时时间(毫秒) spring.redis.timeout=5000
package com.example.demo.Util; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; @Component public class RedisUtil { @Autowired private RedisTemplate<String,String> redisTemplate; /** * 读取缓存 * @param key * @return */ public String get(final String key){ return redisTemplate.opsForValue().get(key); } /** * 写入缓存 * @param key * @param value * @return */ public boolean set(final String key,String value){ boolean result = false; try { redisTemplate.opsForValue().set(key,value); result = true; } catch (Exception e){ e.printStackTrace(); } return result; } /** * 更新缓存 * @param key * @param value * @return */ public boolean update(final String key,String value){ boolean result = false; try { redisTemplate.opsForValue().getAndSet(key,value); result = true; } catch (Exception e){ e.printStackTrace(); } return result; } /** * 删除缓存 * @param key * @return */ public boolean delete(final String key){ boolean result = false; try { redisTemplate.delete(key); result = true; } catch (Exception e){ e.printStackTrace(); } return result; } }
Insertion operation:
/** * 插入一个key为"username",value为"supper"的键值对 */ @Test public void set(){ redisUtil.set("username","supper"); }
Running result:
127.0.0.1: 6379> get username "supper"
Read operation:
/** * 读取key为"username"的值 */ @Test public void get(){ System.out.println(redisUtil.get("username")); }
Run result:
supper
Update operation:
/** * 将key为"username"的键值对的值更新为"chen" */ @Test public void update(){ redisUtil.update("username","chen"); }
Run result:
127.0.0.1: 6379> get username "chen"
Delete operation:
/** * 删除key为"username"的键值对 */ @Test public void del(){ redisUtil.delete("username"); }
Run result:
127.0.0.1: 6379> get username (nil)
The above is the detailed content of What are the methods of using Redis cache in SpringBoot?. For more information, please follow other related articles on the PHP Chinese website!