基本使用
依賴和配置
依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置
spring:
redis:
database: 0
host: localhost
port: 6379
password:
jedis:
pool:
max-active: 8 #=最大連接數(使用負值表示沒有限制)
max-wait: -1s #最大阻塞時間(使用負值表示沒有限制)
max-idle: 8 #最大空閒連接
min-idle: 0 #最小空閒連接
timeout: 10s
使用
@RestController
@RequestMapping("/redis")
public class RedisResource {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@PostMapping("/test")
public String test(@RequestParam(defaultValue = "key") String key, @RequestParam(defaultValue = "val") String val) {
stringRedisTemplate.opsForValue().set(key, val);
return "key:" + key + ", val=" + stringRedisTemplate.opsForValue().get(key);
}
}
測試
寫個啓動類,啓動後訪問 http://localhost:8080/redis/test?key=a&val=abc
查看redis
$ telnet localhost 6379
Trying ::1...
Connected to localhost.
Escape character is '^]'.
$ get a
abc
CacheManager緩存管理
使用cacheManager,結合spring可以使用@Cacheable
、@CachePut
、@CacheEvict
添加到方法上面,來基於方法參數和返回值看來操作緩存
RedisConfig配置
@Configuration
@EnableCaching
public class RedisCachingConfigurer extends CachingConfigurerSupport {
private static final Duration timeToLive = Duration.ZERO;
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解決查詢緩存轉換異常的問題
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解決亂碼的問題)
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(timeToLive)
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}
註解操作緩存
@Service
@Slf4j
public class UserService {
private Map<Integer, User> data = new ConcurrentHashMap<>(10);
//添加緩存
@Cacheable(value = "userCache", key = "#id", unless = "#result==null")
public User get(int id){
log.info("不走redis緩存,查詢用戶,id={}", id);
return data.get(id);
}
//修改緩存
@CachePut(value = "userCache", key = "#id")
public User save(int id, String name){
data.put(id, new User(id, name));
return data.get(id);
}
//刪除緩存
@CacheEvict(value = "userCache", key = "#p0")
public void del(int id){
data.remove(id);
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class User implements Serializable{
private int id;
private String name;
}
}
接口測試
@RestController
@RequestMapping("/redis")
public class RedisResource {
@Autowired private StringRedisTemplate stringRedisTemplate;
@Autowired private UserService userService;
@PostMapping("/test")
public String test(@RequestParam(defaultValue = "key") String key, @RequestParam(defaultValue = "val")String val){
stringRedisTemplate.opsForValue().set(key, val);
return "key:" + key + ", val=" + stringRedisTemplate.opsForValue().get(key);
}
/**--------------cacheManager測試--------------*/
@GetMapping("/user")
public UserService.User get(int id){
return userService.get(id);
}
@PostMapping("/user")
public UserService.User save(int id, String name){
return userService.save(id, name);
}
@DeleteMapping("/user")
public String del(int id){
userService.del(id);
return "delete success.";
}
}
啓動項目後,測試。第一次redis沒有任何緩存值
GET http://localhost:8080/redis/user?id=1
控制檯打印:
[nio-8080-exec-4] c.yimingkeji.redis.service.UserService : 不走redis緩存,查詢用戶,id=1
然後調用post方法來添加緩存
POST http://localhost:8080/redis/user?id=1&name=哈哈哈
{
"id": 1,
"name": "哈哈哈"
}
再次查詢
GET http://localhost:8080/redis/user?id=1
{
"id": 1,
"name": "哈哈哈"
}
查看redis
然後再調用delete方法刪除緩存
DELETE http://localhost:8080/redis/user?id=1
再次查看redis