POM
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.6</version> <relativePath/> </parent> <groupId>org.example</groupId> <artifactId>nemo</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.6.6</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.80</version> </dependency> </dependencies> </project>
application.properties
#redis spring.redis.host=192.168.1.7 #Redis服务器连接端口 spring.redis.port=6379 #连接池最大连接数(使用负值表示没有限制) spring.redis.pool.max-active=8 #连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.pool.max-wait=-1 #连接池中的最大空闲连接 spring.redis.pool.max-idle=8 #连接池中的最小空闲连接 spring.redis.pool.min-idle=0 #连接超时时间(毫秒) spring.redis.timeout=30000
代码
Controller
@RestController public class CacheController { @Autowired private CacheService cacheService; @RequestMapping("/getValue") public String getValue(String key){ return cacheService.get(key); } @RequestMapping("/add") public Boolean add(String key, String value) { cacheService.add(key,value); return true; } }
Service
public interface CacheService { <K, V> void add(K key, V value); <K> String get(K key); }
ServiceImpl
@Service public class CacheServiceImpl implements CacheService { @Resource private RedisTemplate<Object, String> redisTemplate; /** * 添加key */ @Override public <K, V> void add(K key, V value) { try { if (value != null) { redisTemplate .opsForValue() .set(key, JSON.toJSONString(value)); } } catch (Exception e) { throw new RuntimeException("数据缓存至redis失败"); } } /** * 获得 */ @Override public <K> String get(K key) { String value; try { value = redisTemplate.opsForValue().get(key); } catch (Exception e) { throw new RuntimeException("从redis缓存中获取缓存数据失败"); } return value; } /** * 删除key */ public void delete(String key) { redisTemplate.delete(key); } }