Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

第 49 章 Spring Data with Redis

目录

49.1. 集成 Redis XML 方式
49.1.1. pom.xml
49.1.2. springframework-servlet.xml
49.1.3. Controller
49.1.4. index.jsp
49.1.5. 测试
49.2. 通过构造方法实例化 Redis
49.3. stringRedisTemplate 基本用法
49.4. RedisTemplate
49.4.1. 设置缓存时间
49.4.2. increment
49.4.3. 删除 key
49.4.4. 对象存储
49.4.5. 获取过期时间
49.4.6. 过期时间未执行
49.5. ValueOperations
49.5.1. 字符串截取
49.5.2. 追加字符串
49.5.3. 设置键的字符串值并返回其旧值
49.5.4. 返回字符串长度
49.5.5. 如果key不存便缓存。
49.5.6. 缓存多个值 /获取多个值 multiSet / multiGet
49.5.7. setBit / getBit 二进制位操作
49.6. 列表操作
49.6.1. rightPush
49.6.2. rightPushAll
49.6.3. rightPushIfPresent
49.6.4. leftPush
49.6.5. leftPushAll
49.6.6. range
49.7. SetOperations 数据类型
49.7.1. 返回集合中的所有成员
49.7.2. 取出一个成员
49.7.3. 随机获取无序集合中的一个元素
49.7.4. 随机获取 n 个成员(存在重复数据)
49.7.5. 随机获取 n 个不重复成员
49.7.6. 在两个 SET 间移动数据
49.7.7. 成员删除
49.7.8. 返回集合数量
49.7.9. 判断元素是否在集合成员中
49.7.10. 对比两个集合求交集
49.7.11. 对比两个集合求交集,然后存储到新的 key 中
49.7.12. 合并两个集合,并去处重复数据
49.7.13. 合并两个集合去重复后保存到新的 key 中
49.7.14. 计算两个合集的差集
49.7.15. 计算两个合集的差集,然后保存到新的 key 中
49.7.16. 遍历 SET 集合
49.8. ZSetOperations 有序的 set 集合
49.9. HashOperations
49.9.1. put
49.9.2. putAll
49.9.3. 从键中的哈希获取给定hashKey的值
49.9.4. delete
49.9.5. 确定哈希hashKey是否存在
49.9.6. 从哈希中获取指定的多个 hashKey 的值
49.9.7. 只有hashKey不存在时才能添加值
49.9.8. 获取整个Hash
49.9.9. 获取所有key
49.9.10. 通过 hashKey 获取所有值
49.9.11. 值加法操作
49.9.12. 遍历 Hash 表
49.10. 存储 Json 对象
49.10.1. 集成 RedisTemplate 定义新类 JsonRedisTemplate
49.10.2. 配置 Redis
49.10.3. 测试
49.11. Spring Data Redis - Repository Examples
49.11.1. @EnableRedisRepositories 启动 Redis 仓库
49.11.2. 定义 Domain 类
49.11.3. Repository 接口
49.11.4. 测试代码
49.12. CacheService
49.13. FAQ
49.13.1. Spring Data Redis

49.1. 集成 Redis XML 方式

49.1.1. pom.xml

		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-redis</artifactId>
		</dependency>			
		
			

49.1.2. springframework-servlet.xml

		
	<!-- Redis Connection Factory -->
	<bean id="jedisConnFactory"
		class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
		p:host-name="192.168.2.1" p:port="6379" p:use-pool="true" />

	<!-- redis redisTemplate definition -->
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
		p:connection-factory-ref="jedisConnFactory" />
		
			

例 49.1. Spring Data Redis Example

			
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
	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
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">

	<mvc:resources location="/images/" mapping="/images/**" />
	<mvc:resources location="/css/" mapping="/css/**" />

	<context:component-scan base-package="cn.netkiller.controller" />

	<mvc:annotation-driven />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
		<!-- <property name="viewNames" value="*.jsp" /> -->
	</bean>

	<bean id="configuracion"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:resources/development.properties" />
	</bean>

	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="cn.netkiller.mapper" />
	</bean>

	<bean id="userService" class="cn.netkiller.service.UserService">
	</bean>

	<!-- Redis Connection Factory -->
	<bean id="jedisConnFactory"
		class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
		p:host-name="192.168.2.1" p:port="6379" p:use-pool="true" />

	<!-- redis redisTemplate definition -->
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
		p:connection-factory-ref="jedisConnFactory" />
</beans>				
			
				

49.1.3. Controller

		
package cn.netkiller.controller;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.netkiller.model.User;

@Controller
public class CacheController {

	// inject the actual redisTemplate
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	// inject the redisTemplate as ListOperations
	@Resource(name = "redisTemplate")
	private ListOperations<String, String> listOps;

	@RequestMapping("/cache")
	public ModelAndView cache() {

		String message = "";

		User user = new User();
		user.setId("1");
		user.setName("Neo");
		user.setAge(30);

		String key = "user";
		listOps.leftPush(key, user.toString());
		message = listOps.leftPop(key);

		redisTemplate.setKeySerializer(new StringRedisSerializer());
		redisTemplate.setValueSerializer(new StringRedisSerializer());
		redisTemplate.opsForValue().set("key", user.toString());

		return new ModelAndView("index/index", "variable", message);
	}
}
		
			

49.1.4. index.jsp

		
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<br>
	<div style="text-align:center">
		<h2>
			${variable}
		</h2>
	</div>
</body>
</html>			
		
			

49.1.5. 测试

请求URL http://your.domain.com/your.html

		
[root@master ~]# redis-cli 
redis 127.0.0.1:6379> keys *
1) "\xac\xed\x00\x05t\x00\x04user"
2) "key"

redis 127.0.0.1:6379> get key
"\xac\xed\x00\x05t\x00\x1dUser [id=1, name=Neo, age=30]"
		
			
[提示]提示

Spring Redis 默认使用 Byte数据类型存储Key,在redis-cli中会看到 "\xac\xed\x00\x05t\x00\x04" 前缀不方便get操作,所以我们会设置使用字符串,通过 redisTemplate.setKeySerializer(new StringRedisSerializer()); 实现