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

第 74 章 Spring Data with Redis

目录

74.1. 集成 Redis XML 方式
74.1.1. pom.xml
74.1.2. springframework-servlet.xml
74.1.3. Controller
74.1.4. index.jsp
74.1.5. 测试
74.2. 通过构造方法实例化 Redis
74.3. stringRedisTemplate 基本用法
74.4. RedisTemplate
74.4.1. 设置缓存时间
74.4.2. increment
74.4.3. 删除 key
74.4.4. 对象存储
74.4.5. 获取过期时间
74.4.6. 过期时间未执行
74.5. ValueOperations
74.5.1. 字符串截取
74.5.2. 追加字符串
74.5.3. 设置键的字符串值并返回其旧值
74.5.4. 返回字符串长度
74.5.5. 如果key不存便缓存。
74.5.6. 缓存多个值 /获取多个值 multiSet / multiGet
74.5.7. setBit / getBit 二进制位操作
74.6. 列表操作
74.6.1. rightPush
74.6.2. rightPushAll
74.6.3. rightPushIfPresent
74.6.4. leftPush
74.6.5. leftPushAll
74.6.6. range
74.7. SetOperations 数据类型
74.7.1. 返回集合中的所有成员
74.7.2. 取出一个成员
74.7.3. 随机获取无序集合中的一个元素
74.7.4. 随机获取 n 个成员(存在重复数据)
74.7.5. 随机获取 n 个不重复成员
74.7.6. 在两个 SET 间移动数据
74.7.7. 成员删除
74.7.8. 返回集合数量
74.7.9. 判断元素是否在集合成员中
74.7.10. 对比两个集合求交集
74.7.11. 对比两个集合求交集,然后存储到新的 key 中
74.7.12. 合并两个集合,并去处重复数据
74.7.13. 合并两个集合去重复后保存到新的 key 中
74.7.14. 计算两个合集的差集
74.7.15. 计算两个合集的差集,然后保存到新的 key 中
74.7.16. 遍历 SET 集合
74.8. ZSetOperations 有序的 set 集合
74.9. HashOperations
74.9.1. put
74.9.2. putAll
74.9.3. 从键中的哈希获取给定hashKey的值
74.9.4. delete
74.9.5. 确定哈希hashKey是否存在
74.9.6. 从哈希中获取指定的多个 hashKey 的值
74.9.7. 只有hashKey不存在时才能添加值
74.9.8. 获取整个Hash
74.9.9. 获取所有key
74.9.10. 通过 hashKey 获取所有值
74.9.11. 值加法操作
74.9.12. 遍历 Hash 表
74.10. 存储 Json 对象
74.10.1. 集成 RedisTemplate 定义新类 JsonRedisTemplate
74.10.2. 配置 Redis
74.10.3. 测试
74.11. Spring Data Redis - Repository Examples
74.11.1. @EnableRedisRepositories 启动 Redis 仓库
74.11.2. 定义 Domain 类
74.11.3. Repository 接口
74.11.4. 测试代码
74.12. CacheService
74.13. FAQ
74.13.1. Spring Data Redis

74.1. 集成 Redis XML 方式

74.1.1. pom.xml

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

74.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" />
		
			

例 74.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>				
			
				

74.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);
	}
}
		
			

74.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>			
		
			

74.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()); 实现