北京尚学堂|百战卓越班学员学习经验分享:SpringBoot缓存技术

来自尚学堂百战卓越班学员知乎左新宇的学习分享。

一、缓存技术

(1) 什么是Ehcache?

Ehcache是一种开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器

(2)SpringBoot整合Ehcache

1、在 pom 文件中添加 Ehcache 的坐标

2、创建Ehcache的配置文件

文件名:ehcache.xml

位置:src/main/resources/ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

<diskStore path="java.io.tmpdir"/>

<!--defaultCache:echcache 的默认缓存策略 -->

<defaultCache

maxElementsInMemory="10000"

eternal="false"

timeToIdleSeconds="120"

timeToLiveSeconds="120"

maxElementsOnDisk="10000000"

diskExpiryThreadIntervalSeconds="120"

memoryStoreEvictionPolicy="LRU">

<persistence strategy="localTempSwap"/>

</defaultCache>

<!-- 自定义缓存策略 -->

<cache name="users"

maxElementsInMemory="10000"

eternal="false" timeToIdleSeconds="120"

timeToLiveSeconds="120"

maxElementsOnDisk="10000000"

diskExpiryThreadIntervalSeconds="120"

memoryStoreEvictionPolicy="LRU">

<persistence strategy="localTempSwap"/>

</cache>

</ehcache>

3、修改 application.properties 文件

添加 spring.cache.ehcache.cofnig=ehcache.xml

4、修改启动类

@SpringBootApplication 
@EnableCaching
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args); }
}

5、创建业务层

//@Cacheable:对当前查询的对象做缓存处理 
@Cacheable(value="users")
public Users findUserById(Integer id) {
return this.usersRepository.findOne(id);
}

6、实体类实现序列化

@Cacheable 作用:把方法的返回值添加到 Ehcache 中做缓存

Value 属性:指定一个 Ehcache 配置文件中的缓存策略,如果么有给定 value,name 则表示使用默认的缓存策略。

<!-- 自定义缓存策略 --> 
<cache name="users"
maxElementsInMemory="10000"
eternal="false" timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</cache>

Key 属性:给存储的值起个名称。在查询时如果有名称相同的,那么则知己从缓存中将 数据返回

@Override 
@Cacheable(value="users",key="#pageable.pageSize")
public Page<Users> findUserByPage(Pageable pageable) {
return this.usersRepository.findAll(pageable);
}

@CacheEvict 作用:清除缓存

@CacheEvict(value="users",allEntries=true) 
public void saveUsers(Users users) {
this.usersRepository.save(users); }
}

二、 SpringBoot 整合 SpringDataRedis

SpringDataRedis 是属于 SpringData 下的一个模块。作用就是简化对于 redis 的操做

1、 pom 文件添加 SpringDataRedis 的启动器

2、编写 SpringDataRedis 的配置类

@Configuration 
public class RedisConfig {
/**
* 1.创建 JedisPoolConfig 对象。在该对象中完成一些链接池配置
* */
@Bean
public JedisPoolConfig jedisPoolConfig(){
JedisPoolConfig config = new JedisPoolConfig();
//最大空闲数 config.setMaxIdle(10);
//最小空闲数 config.setMinIdle(5);
//最大链接数 config.setMaxTotal(20);
return config;
}
/**
* 2.创建 JedisConnectionFactory:配置 redis 链接信息
*/
@Bean
public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig config){
JedisConnectionFactory factory = new JedisConnectionFactory();
//关联链接池的配置对象
factory.setPoolConfig(config);
//配置链接 Redis 的信息
//主机地址
factory.setHostName("192.168.70.128");
//端口
factory.setPort(6379);
return factory;
}
/**
* 3.创建 RedisTemplate:用于执行 Redis 操作的方法
*/
@Bean
public RedisTemplate<String,Object> redisTemplate(JedisConnectionFactory factory){
RedisTemplate<String, Object> template = new RedisTemplate<>();
//关联
template.setConnectionFactory(factory);
//为 key 设置序列化器
template.setKeySerializer(new StringRedisSerializer());
//为 value 设置序列化器
template.setValueSerializer(new StringRedisSerializer());
return template;
}
}

测试

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringBootTest(classes=App.class)
public class RedisTest {
@Autowired private RedisTemplate<String, Object> redisTemplate;
/**
* 添加一个字符串
*/
@Test public void testSet(){
this.redisTemplate.opsForValue().set("key", "北京尚学堂"); }
/**
* 获取一个字符串
*/
@Test public void testGet(){
String value = (String)this.redisTemplate.opsForValue().get("key");
System.out.println(value); } }

更多科技一手咨询,欢迎关注!

“我们相信人人都可以成为一个IT大神,现在开始,选择一条阳光大道,助你入门,学习的路上不再迷茫。这里是北京尚学堂,初学者转行到IT行业的聚集地。"

发表评论
留言与评论(共有 0 条评论)
   
验证码:

相关文章

推荐文章

'); })();