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

第 77 章 Spring Data with Redis

目录

77.1. 集成 Redis XML 方式
77.1.1. pom.xml
77.1.2. springframework-servlet.xml
77.1.3. Controller
77.1.4. index.jsp
77.1.5. 测试
77.2. 通过构造方法实例化 Redis
77.3. stringRedisTemplate 基本用法
77.4. RedisTemplate
77.4.1. 设置缓存时间
77.4.2. increment
77.4.3. 删除 key
77.4.4. 对象存储
77.4.5. 获取过期时间
77.4.6. 过期时间未执行
77.5. ValueOperations
77.5.1. 字符串截取
77.5.2. 追加字符串
77.5.3. 设置键的字符串值并返回其旧值
77.5.4. 返回字符串长度
77.5.5. 如果key不存便缓存。
77.5.6. 缓存多个值 /获取多个值 multiSet / multiGet
77.5.7. setBit / getBit 二进制位操作
77.6. 列表操作
77.6.1. rightPush
77.6.2. rightPushAll
77.6.3. rightPushIfPresent
77.6.4. leftPush
77.6.5. leftPushAll
77.6.6. range
77.7. SetOperations 数据类型
77.7.1. 返回集合中的所有成员
77.7.2. 取出一个成员
77.7.3. 随机获取无序集合中的一个元素
77.7.4. 随机获取 n 个成员(存在重复数据)
77.7.5. 随机获取 n 个不重复成员
77.7.6. 在两个 SET 间移动数据
77.7.7. 成员删除
77.7.8. 返回集合数量
77.7.9. 判断元素是否在集合成员中
77.7.10. 对比两个集合求交集
77.7.11. 对比两个集合求交集,然后存储到新的 key 中
77.7.12. 合并两个集合,并去处重复数据
77.7.13. 合并两个集合去重复后保存到新的 key 中
77.7.14. 计算两个合集的差集
77.7.15. 计算两个合集的差集,然后保存到新的 key 中
77.7.16. 遍历 SET 集合
77.8. ZSetOperations 有序的 set 集合
77.9. HashOperations
77.9.1. put
77.9.2. putAll
77.9.3. 从键中的哈希获取给定hashKey的值
77.9.4. delete
77.9.5. 确定哈希hashKey是否存在
77.9.6. 从哈希中获取指定的多个 hashKey 的值
77.9.7. 只有hashKey不存在时才能添加值
77.9.8. 获取整个Hash
77.9.9. 获取所有key
77.9.10. 通过 hashKey 获取所有值
77.9.11. 值加法操作
77.9.12. 遍历 Hash 表
77.10. 存储 Json 对象
77.10.1. 集成 RedisTemplate 定义新类 JsonRedisTemplate
77.10.2. 配置 Redis
77.10.3. 测试
77.11. Spring Data Redis - Repository Examples
77.11.1. @EnableRedisRepositories 启动 Redis 仓库
77.11.2. 定义 Domain 类
77.11.3. Repository 接口
77.11.4. 测试代码
77.12. CacheService
77.13. FAQ
77.13.1. Spring Data Redis

77.1. 集成 Redis XML 方式

77.1.1. pom.xml

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

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

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

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

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

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