第 8 章 Spring Data

8.1. Spring Data Redis

8.1.1. pom.xml

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

8.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 template definition -->
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
		p:connection-factory-ref="jedisConnFactory" />

例 8.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 template definition -->
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
		p:connection-factory-ref="jedisConnFactory" />
</beans>				

8.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 template
	@Autowired
	private RedisTemplate<String, String> template;

	// inject the template 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);

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

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

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

8.1.5. 删除 key

	private void cleanNewToday() {
		long begin = System.currentTimeMillis();

		redisTemplate.delete("news:today");

        long end = System.currentTimeMillis();
		logger.info("Schedule clean redis {} 耗时 {} 秒", "cleanNewFlash()", (end-begin) / 1000 );
	}

8.1.6. 测试

请求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操作,所以我们会设置使用字符串,通过 template.setKeySerializer(new StringRedisSerializer()); 实现

8.1.7. ZSET 数据类型

//添加 一个 set 集合
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add("Member", "neo");
set.add("Member", "36");
set.add("Member", "178cm");
//输出 set 集合
System.out.println(set.members("Member"));

//添加有序的 set 集合
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add("zMember", "neo", 0);
zset.add("zMember", "36", 1);
zset.add("zMember", "178cm", 2);
//输出有序 set 集合
System.out.println(zset.rangeByScore("zMember", 0, 2));		
package cn.netkiller.api.restful;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import common.pojo.ResponseRestful;

@RestController
@RequestMapping("/news")
public class NewsRestController {

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@RequestMapping(value = "/flash/{count}")
	public ResponseRestful flash(@PathVariable("count") long count) {
		if(count == 0L) {
			count=10L;
		}
		Set<String> news = this.redisTemplate.opsForZSet().reverseRange("news:flash", 0, count);
		if (news == null) {
			return new ResponseRestful(false, 10, "没有查询到结果", news);
		}
		return new ResponseRestful(true, 0, "返回数据: " + news.size() + " 条", news);
	}

	public void addRecentUser(long userId, String name) {
	    String key = RedisKeyGenerator.genRecentBrowsingPositionsKey(String.valueOf(userId));
	    // 获取已缓存的最近浏览的职位
	    ZSetOperations<String, String> zSetOperations = redisTempalte.opsForZSet();
        //zset内部是按分数来排序的,这里用当前时间做分数
	    zSetOperations.add(key, name, System.currentTimeMillis());
	    zSetOperations.removeRange(key, 0, -6);
	}  

}

8.1.8. Hash

HashOperations<String, Object, Object>  hash = redisTemplate.opsForHash();
Map<String,Object> map = new HashMap<String,Object>();
map.put("name", "neo");
map.put("age", "36");
hash.putAll("member", map);

System.out.println(hash.entries("member"));		

8.1.9. List

ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush("books", "Linux");
list.rightPush("books", "Java");
System.out.println(list.range("books", 0, 1));

原文出处:Netkiller 系列 手札
本文作者:陈景峯
转载请与作者联系,同时请务必标明文章原始出处和作者信息及本声明。

时间: 2025-01-02 10:49:41

第 8 章 Spring Data的相关文章

第 5 章 Spring Data

5.1. Spring Data Redis 5.1.1. pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency> 5.1.2. springframework-servlet.xml <!-- Redis Connection

Spring Data 数据库建模最佳实践

本文节选自电子书<Netkiller Architect 手札> 出处:http://www.netkiller.cn 作者:netkiller , QQ:13721218, 订阅号:netkiller-ebook 第 12 章 Spring Data 数据库建模最佳实践 目录 12.1. 分类表 12.2. 为字段增加索引 12.3. 复合索引 12.4. 一对多实例 12.5. ManyToMany 多对多 12.6. 外键级联删除 ORM的出现解决了程序猿学习数据库学历成本,也加快了开发

《Spring Data实战》——第1章 Spring Data项目 1.1为Spring开发人员提供的NoSQL数据访问功能

第一部分 背景知识 第1章 Spring Data项目 Spring Data项目是在"Spring One 2010开发者大会"上创建的,该项目起源于当年早些时候Rod Johnson(SpringSource)和Emil Eifrem(Neo Technologies)共同参与的一场黑客会议.他们试图把Neo4j图形数据库整合到Spring框架中,并评估了各种不同的方式.这次会议最终为初始版本的Spring Data Neo4j模块奠定了基础,这个新的SpringSource项目旨

《Spring Data实战》——第2章 Repository:便利的数据访问层 2.1快速入门

第2章 Repository:便利的数据访问层 长期以来,实现应用程序的数据访问层一直是件繁琐的工作,因为我们经常需要编写大量的样板式代码,而且贫血(anemic)的领域类并没有按照真正面向对象或领域驱动方式来进行设计.因此Spring Data Repository抽象的目标就是大幅简化各种持久化存储持久层的实现.我们将会使用Spring Data JPA模块作为例子来讨论Repository抽象的基本理念.对于其他类型的存储,可以参考对应的例子. 2.1 快速入门 我们选取领域模型中的Cus

Spring Boot 2.x 小新功能 – Spring Data Web configuration

本文提纲 一.前言 二.运行 chapter-5-spring-boot-paging-sorting 工程 三.chapter-5-spring-boot-paging-sorting 工程配置详解 四.小结 运行环境: Mac OS 10.12.x JDK 8 + Spring Boot 2.0.0.M4  一.前言 Spring 2.x 更新了一个小小的功能即: Spring Data Web configuration Spring Boot exposes a new spring.d

Spring Data JPA方法定义规范【从零开始学Spring Boot】

视频&交流平台] à SpringBoot网易云课堂视频 http://study.163.com/course/introduction.htm?courseId=1004329008 à Spring Boot交流平台 http://412887952-qq-com.iteye.com/blog/2321532           事情的起因:有人问过我们这个这个问题:为什么我利用Spring data jpa写的方法没有按照我想要的情况进行执行呢?我记得当时只是告诉他你你先看看Spring

《Spring Data实战》——导读

前言 数据访问领域在过去的7年间发生了重要的变化.过去30年间一直占据企业级数据存储和处理核心位置的关系型数据库已经不能再独领风骚了.在过去的7年间诞生了很多可选的数据存储形式,当然也有的面临着消亡,它们被使用到了带有关键任务的企业级应用程序之中.这些新的数据存储形式是为了解决特定的数据访问问题而设计的,使用关系型数据库通常无法高效地解决这些问题. 将关系型数据库推到拐点的一个问题就是扩展性(scale).试问,我们如何将几百甚至几千TB(terabyte)的数据存储到关系型数据库中?这个问题让

使用Spring Data 仓库工作 4.1-4.3

Spring Data 仓库抽象的目标是为了明显减少为了各种持久存储的来实现的数据访问层的样板代码量. Spring Data存储库文档和你的模块 本章解释了Spring Data 存储库的核心观念,以及接口.本章的信息来自Spring Data公共模块.它使用了Java Persistence API(JPA)中的配置以及代码实例.将命名空间声明和要扩展的类型扩展为你将会使用的模块的等效项.命名空间引用包含了所有被Spring Data模块支持的存储库API的XML配置,存储库查询关键字包含了

《Spring实战(第4版)》——第1章 Spring之旅 1.1简化Java开发

第1部分 Spring的核心 Spring可以做很多事情,它为企业级开发提供给了丰富的功能,但是这些功能的底层都依赖于它的两个核心特性,也就是依赖注入(dependency injection,DI)和面向切面编程(aspect-oriented programming,AOP). 作为本书的开始,在第1章"Spring之旅"中,我将快速介绍一下Spring框架,包括Spring DI和AOP的概况,以及它们是如何帮助读者解耦应用组件的. 在第2章"装配Bean"中