Spring 原生的缓存 SimpleCacheManager
配置:类似于 TransactionManager 的配置,参见 Spring 事务 Transaction 开发实践
<bean id="cacheManager" class="SimpleCacheManager">
<property name="caches">
<set>
<!-- 可以设置多个 -->
<bean class="ConcurrentMapCacheFactoryBean"
p:name="students" />
</set>
</property>
</bean>
<cache:annotation-driver cache-manager="cacheManager" />
添加缓存:@Cachable
注解
@Cachable(value="students")
public List<Student> getStudents() {
...
}
更新缓存:@CachePut
注解
@CachePut(value="students")
public List<Student> updateStudents() {
...
}
删除缓存:@CacheEvict
注解
@CacheEvict(value="students", allEntries=true)
public void deleteStudents() {
...
}
Redis 介绍
key - value 存储系统(可以存储 string, map, list, set, sorted set),运行在内存中,也可以持久化到磁盘中。
Mac 下的安装:
下载 https://redis.io/download。
本地解压并移动到 /usr/local
:
tar zxvf redis-4.0.10.tar.gz
sudo mv redis-4.0.10 /usr/local
cd /usr/local/redis-4.0.10
sudo make test
sudo make install
启动:redis-server
进入命令行与 redis server 进行交互:redis-cli
127.0.0.1:6379> set name "Tom"
OK
127.0.0.1:6379> get name
"Tom"
127.0.0.1:6379> lpush students Tom
(integer) 1
127.0.0.1:6379> lpush students Lily
(integer) 2
127.0.0.1:6379> lrange students 0 10
1) "Lily"
2) "Tom"
127.0.0.1:6379> hmset uses name Tom age 25
OK
127.0.0.1:6379> hmget uses name
1) "Tom"
Spring 集成 Redis
redis.properties 配置 Redis 服务器连接信息:
redis.host=localhost
redis.port=6379
redis.pass=123456
redis.maxIdle=300
redis.maxActive=600
redis.maxWait=1000
redis.testOnBorrow=true
Spring 配置:
<bean id="connectionFactory" class="JedisConnectionFactory" p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>
<bean id="redisTemplate" class="StringRedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>
<bean id="cacheManager" class="RedisCacheManager"
c:template-ref="redisTemplate"
/>
<cache:annotation-driver cache-manager="cacheManager" />
添加缓存:@Cachable
注解
@Cachable(key="#id", value="student")
public Student getStudent(int id) {
...
}
更新缓存:@CachePut
注解
@CachePut(key="#student.id", value="student")
public void addStudent(Student student) {
...
}