第零步
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
第一步 application.yml 配置文件 配置
spring:
redis: database: 0 host: 172.18.0.88 port: 6378 password: 123456 jedis: pool: maxActive: 3 maxIdle: 3 maxWait: -1 minIdle: 0 timeout: 15000
第二步 创建工具类
package com.zzh.elite.utils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; /** * redis操作工具类.</br> * (基于RedisTemplate) * @author zzh * 20191217 */ @Component public class RedisUtils { @Autowired private RedisTemplate redisTemplate; /** * 写入缓存 * */ 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; } /** * 读取缓存 * */ public String get(final String key){ return (String) redisTemplate.opsForValue().get(key); } /** * 更新缓存 * */ public boolean getAndSet(final String key,String value){ boolean result=false; try{ redisTemplate.opsForValue().getAndSet(key,value); }catch (Exception e){ e.printStackTrace(); } return result; } /** * 删除缓存 * */ public boolean delete(final String key){ boolean result=false; try { redisTemplate.delete(key); result=true; }catch (Exception e){ e.printStackTrace(); } return result; } }
第三步 测试
package com.zzh.elite.dto; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @Data public class RedisTestDTO { @ApiModelProperty(value="缓存key") private String redisKey; @ApiModelProperty(value="缓存value") private String redisValue; }
@Autowired RedisUtils redisUtils;
@RequestMapping(value = "test/redis",method = RequestMethod.POST) @ApiOperation("redis测试") public ResponseMessage<RedisTestVO> redis(@RequestBody RedisTestDTO redisTestDTO){ redisUtils.set(redisTestDTO.getRedisKey(),redisTestDTO.getRedisValue()); RedisTestVO redisTestVO=new RedisTestVO(); redisTestVO.setRedisKey(redisTestDTO.getRedisKey()); redisTestVO.setRedisValue(redisUtils.get(redisTestDTO.getRedisKey())); return CommonUtils.okResponseVO(redisTestVO); }