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

第 52 章 Spring Data with Redis

目录

52.1. 集成 Redis XML 方式
52.1.1. pom.xml
52.1.2. springframework-servlet.xml
52.1.3. Controller
52.1.4. index.jsp
52.1.5. 测试
52.2. 通过构造方法实例化 Redis
52.3. RedisTemplate
52.3.1. 设置缓存时间
52.3.2. increment
52.3.3. 删除 key
52.3.4. 对象存储
52.3.5. 获取过期时间
52.3.6. 过期时间未执行
52.4. stringRedisTemplate 基本用法
52.5. ValueOperations
52.5.1. 字符串截取
52.5.2. 追加字符串
52.5.3. 设置键的字符串值并返回其旧值
52.5.4. 返回字符串长度
52.5.5. 如果key不存便缓存。
52.5.6. 缓存多个值 /获取多个值 multiSet / multiGet
52.5.7. setBit / getBit 二进制位操作
52.6. 列表操作
52.6.1. rightPush
52.6.2. rightPushAll
52.6.3. rightPushIfPresent
52.6.4. leftPush
52.6.5. leftPushAll
52.6.6. range
52.7. SetOperations 数据类型
52.7.1. 返回集合中的所有成员
52.7.2. 取出一个成员
52.7.3. 随机获取无序集合中的一个元素
52.7.4. 随机获取 n 个成员(存在重复数据)
52.7.5. 随机获取 n 个不重复成员
52.7.6. 在两个 SET 间移动数据
52.7.7. 成员删除
52.7.8. 返回集合数量
52.7.9. 判断元素是否在集合成员中
52.7.10. 对比两个集合求交集
52.7.11. 对比两个集合求交集,然后存储到新的 key 中
52.7.12. 合并两个集合,并去处重复数据
52.7.13. 合并两个集合去重复后保存到新的 key 中
52.7.14. 计算两个合集的差集
52.7.15. 计算两个合集的差集,然后保存到新的 key 中
52.7.16. 遍历 SET 集合
52.8. ZSetOperations 有序的 set 集合
52.9. HashOperations
52.9.1. put
52.9.2. putAll
52.9.3. 从键中的哈希获取给定hashKey的值
52.9.4. delete
52.9.5. 确定哈希hashKey是否存在
52.9.6. 从哈希中获取指定的多个 hashKey 的值
52.9.7. 只有hashKey不存在时才能添加值
52.9.8. 获取整个Hash
52.9.9. 获取所有key
52.9.10. 通过 hashKey 获取所有值
52.9.11. 值加法操作
52.9.12. 遍历 Hash 表
52.10. 存储 Json 对象
52.10.1. 集成 RedisTemplate 定义新类 JsonRedisTemplate
52.10.2. 配置 Redis
52.10.3. 测试
52.11. Spring Data Redis - Repository Examples
52.11.1. @EnableRedisRepositories 启动 Redis 仓库
52.11.2. 定义 Domain 类
52.11.3. Repository 接口
52.11.4. 测试代码
52.12. FAQ
52.12.1. Spring Data Redis

52.1. 集成 Redis XML 方式

52.1.1. pom.xml

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

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

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

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

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

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