springBoot-连接redis
在原来的项目上继续,地址
1 添加maven
<!--redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
2 配置redis
3 redis Service层
这一点,借鉴网上直接复制来的,也可以根据自己的需求,做改动。
IRedisService
@Service public interface IRedisService { /** * 加入元素 * @param key * @param value */ void setValue(String key, Map<String, Object> value); /** * 加入元素 * @param key * @param value */ void setValue(String key, String value); /** * 加入元素 * @param key * @param value */ void setValue(String key, Object value); /** * 获取元素 * @param key */ Object getMapValue(String key); /** * 获取元素 * @param key */ Object getValue(String key); }
RedisServiceImpl
@Service public class RedisServiceImpl implements IRedisService { @Autowired private RedisTemplate redisTemplate; @Override public void setValue(String key, Map<String, Object> value) { ValueOperations<String, Object> vo = redisTemplate.opsForValue(); vo.set(key, value); redisTemplate.expire(key, 1, TimeUnit.HOURS); } @Override public Object getValue(String key) { ValueOperations<String, String> vo = redisTemplate.opsForValue(); return vo.get(key); } @Override public void setValue(String key, String value) { ValueOperations<String, Object> vo = redisTemplate.opsForValue(); vo.set(key, value); redisTemplate.expire(key, 1, TimeUnit.HOURS); } @Override public void setValue(String key, Object value) { ValueOperations<String, Object> vo = redisTemplate.opsForValue(); vo.set(key, value); redisTemplate.expire(key, 1, TimeUnit.HOURS); } @Override public Object getMapValue(String key) { ValueOperations<String, String> vo = redisTemplate.opsForValue(); return vo.get(key); } }
4 测试
@PostMapping(value = "/redis") @ApiOperation(value = "redis接口", notes = "redis接口", httpMethod = "POST") public String redis(){ iRedisService.setValue("redis", "这是redis的测试数据"); Object redis = iRedisService.getValue("redis"); return redis.toString(); }
启动项目,打开我们的swagger
OK 初步redis测试,已完成。