Redis缓存使用
1.jar包及安装包下载
1.1 下载
redis-2.4.5-win64.zip
1.2 安装
redis-server.exe 服务器启动程序
redis-cli.exe 客户端命令行工具
1.3 安装图形化操作工具
redis-desktop-manager-0.7.6.15.exe
Add new Connection 添加新的连接
TTL 是redis的key的有效时间.
2. Jedis使用
2.1 引入maven坐标
<!-- Jedis利用java操作redis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
</dependency>
2.2 基础入门
@Test
public void testRedis(){
// 连接localhost 默认端口6379
Jedis jedis = new Jedis("localhost");
// 10 表示10秒后失效
jedis.set("company", 10 ,"hello 橙子...");
System.out.println(jedis.get("company"));
}
3.(Spring Data Redis使用)
3.1 引入maven坐标
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.2.RELEASW</version>
</dependency>
3.2 在spring配置文件中配置redisTemplate
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- jedis 连接池配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="300"/>
<property name="maxWaitMillis" value="3000"/>
<property name="testOnBorrow" value="true"/>
</bean>
<!-- jedis 连接工厂 -->
<bean id="redisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="localhost" p:port="6379" p:pool-config-ref="poolConfig"
p:database="0"/>
<!-- spring data 提供 redis模板 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="redisConnectionFactory"/>
<!-- 如果不指定 Serializer -->
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
<!-- 将对象转换为字节数据 -->
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer">
</bean>
</property>
</bean>
</beans>
3.3 示例代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class RedisTemplateTest {
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Test
public void testRedis() {
// 保存key value
// 设置30秒失效
redisTemplate.opsForValue().set("code", "123456", 30, TimeUnit.SECONDS);
// 获取redis中对应的值
String code = redisTemplate.opsForValue().get("code")
}
}