前言
这篇主要介绍缓存技术,此篇是个最简单的入门篇,要是我们觉得缓存原来这么简单,集成怎么没有“坑”,那就错,第二篇会带我们一一过下集成遇到的坑。
本篇集成用springboot版本是2.x和1.x是有些不同的,大家需要注意
如配置redis连接,两个版本的redis客户端连接池使用有所不同。
?....
中心:springboot整合redis,如下刚接触redis的同学可以看下这篇文章:
引入依赖:
在pom文件中添加redis依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
配置数据源
spring: #redis配置 redis: host: 115.28.166.XX port: 80XX password: password # 连接超时时间(毫秒) timeout: 18000 database: 0 jedis: pool: max-active: 8 max-idle: 8 max-wait: -1 min-idle: 0
注意更改ip、端口、密码。经过上述两步的操作,你可以访问redis数据了。
Service层
通过redisTemplate来访问redis.
@Service public class RedisService { Logger logger= LoggerFactory.getLogger(RedisService.class); @Autowired private RedisTemplate redisTemplate; /** * 设置缓存 key-value(包含过期时间) * @param key * @param value */ public void set(String key,String value){ ValueOperations<String, String> ops = redisTemplate.opsForValue(); ops.set(key,value,10, TimeUnit.MINUTES);//1分钟过期 } public String getValue(String key){ ValueOperations<String, String> ops = this.redisTemplate.opsForValue(); return ops.get(key); } ... }
单元测试
@RunWith(SpringRunner.class) @SpringBootTest public class Springboot08RedisApplicationTests { public static Logger logger= LoggerFactory.getLogger(Springboot08RedisApplicationTests.class); @Test public void contextLoads() { } @Autowired RedisService redisService; @Test public void testRedis(){ redisService.set("name","spring boot redis"); redisService.set("age","11"); logger.info("输出结果"); logger.info(redisService.getValue("name")); logger.info(redisService.getValue("age")); } ... }
测试结果:
和预期一样...(这里不是重点)
End
单元测试通过,这毫无疑问,但是至于redis更加高级的应用我们可能会遇到很多问题,如下:
1.实体类未 implements Serializable !!!!! implements Serializable?没有空构造参数?
2.@Cacheable(cacheNames="student1",key = "#id")怎么用? 3.No cache could be resolved for 'Builder[public java.util.List com.es.service.evralarm.EvrAlarmCacheService.getEvrAlarmByAccountId(java.lang.String)] caches=[] | key=''EvrAlarm-'+#accountId' | keyGenerator='' | cacheManager='' | cacheResolver='' | condition='' | unless='' | sync='false'' using resolver 'org.springframework.cache.interceptor.SimpleCacheResolver@7fbfc31a'. At least one cache should be provided per cache operation. 4.用实体类返回报错:java.lang.String cannot be cast to com.limp.domain.Student
5.com.limp.domain.Student cannot be cast to com.limp.domain.Student
...
问题就不一一列了,下一篇整理好后晚上再共享,毕竟知识马虎不得。
看到篇的朋友点个关注呗。@架构师速成记
本文暂时没有评论,来添加一个吧(●'◡'●)