SpringBoot27-spingboot数据访问-NoSQL(Redis)
来源:互联网 发布:matlab怎么调用caffe 编辑:程序博客网 时间:2024/06/07 21:01
Redis是一个基于键值对的开源内存数据存储,当然Redis也可以做数据存储。
一,Spring的支持
1,配置
Spring对Redis的支持也是通过Spring Data Redis来实现的,Spring Data JPA为我们提供了连接相关的ConnectionFactory和数据操作相关的RedisTemplate。在这里需要注意,Spring Data Redis值对Redis2.6和2.8版本做过测试。
根据Redis的不同的Java客户端,Spring Data Redis提供了如下的ConnectionFactory:
JedisConnectionFactory:使用Jedis作为Redis客户端。
JredisConnectionFactory:使用Jredis作为Redis客户端。
LettuceConnectionFactory:使用Lettuce作为Redis客户端。
SrpConnectionFactory:使用Spullara/redis-protocol作为Redis客户端。
配置方式如下:
@Bean public RedisConnectionFactory redisConnectionFactory(){ return new JedisConnectionFactory(); }
RedisTemplate配置方式如下:
@Bean public RedisTemplate<Object,Object> redisTemplate()throws UnknownHostException{ RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory()); return template; }
2,使用
Spring Data Redis为我们提供了RedisTemplate和StringRedisTemplate两个模板来进行数据操作,其中,StringRedisTemplate只针对键值都是字符型的数据进行操作。
RedisTemplate和StringRedisTemplate提供的主要数据访问方法如下:
opsForValue():操作只有简单属性的数据
opsForList():操作含有list的数据
opsForSet():操作含有set的数据
opsForZSet():操作含有ZSet(有序的set)的数据
opsForHash():操作含有hash的数据
更多关于Spring Data Redis的操作,可以查看Spring Data Redis的官方文档。
3,定义Serializer
当我们的数据存储到Redis的时候,我们的键key和值value都是通过Spring提供的Serializer序列化到数据库的。RedisTemplate默认使用的是JdkSerializationRedisSerializer,StringRedisTemplate默认使用的是StringRedisSerializer。
Spring Data JPA为我们提供了下面的Serializer:
GenericToStringSerializer,Jackson2JsonRedisSerializer,JacksonJsonRedisSerializer,JdkSerializationRedisSerializer,OxmSerializer,StringRedisSerializer.
二,Spring Boot的支持
Spring boot对Redis的支持,org.springframework.boot.autoconfigure.data.redis包如下所示:
RedisAutoConfiguration为我们默认配置了JedisConnectionFactory,RedisTemplate以及StringRedisTemplate,让我们可以直接使用Redis作为数据存储。
RedisProperties向我们展示了可以使用以“spring.redis”为前缀的属性在application.properties中配置Redis,主要属性如下:
#数据库名称,默认为db0spring.redis.database=0#服务器地址,默认为localhostspring.redis.host=localhost#数据库密码spring.redis.password=#连接端口号,默认为6379spring.redis.port=6379#连接池设置spring.redis.pool.max-idle=8spring.redis.pool.min-idle=0spring.redis.pool.max-active=8spring.redis.pool.max-wait=-1spring.redis.sentinel.master=spring.redis.sentinel.nodes=spring.redis.timeout=
三,实战
1,安装Redis
1)非Docker安装。若不基于Docker安装的话,我们可以到http://redis.io/download下载合适的版本的Redis。注意不要下载最新版本的3.0.x版本。
2)Docker安装。
下载Redis镜像,docker pull hub.c.163.com/library/redis:latest
通过下面命令运行容器:
docker run -d --name redis容器名 -p 6379:6379 redis镜像id
Redis数据管理可以使用Redis Client,下载地址为:https://github.com/caoxinyu/RedisClient,这是一个可以独立运行的jar包,如下:
2,新建spring boot项目
搭建Spring Boot项目,依赖为redis,web
pom.xml代码如下:
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.jack</groupId><artifactId>springboot10redis</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>springboot10redis</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.7.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.39</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
application.properties的配置如下:
server.port=9090#数据库名称,默认为db0spring.redis.database=0#服务器地址,默认为localhostspring.redis.host=192.168.0.102#数据库密码#spring.redis.password=#连接端口号,默认为6379spring.redis.port=6379#连接池设置spring.redis.pool.max-idle=8spring.redis.pool.min-idle=0spring.redis.pool.max-active=8spring.redis.pool.max-wait=-1#spring.redis.sentinel.master=#spring.redis.sentinel.nodes=#spring.redis.timeout=
3,领域模型类
package com.jack.springboot10redis.entity;import java.io.Serializable;/** * create by jack 2017/10/11 * 此类需要用时间序列化接口,因为使用Jackson做序列化需要一个空构造函数 */public class Person implements Serializable{ private String id; private String name; private Integer age; public Person() { super(); } public Person(String id, String name, Integer age) { super(); this.id = id; this.name = name; this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; }}
4,数据访问
package com.jack.springboot10redis.dao;import com.jack.springboot10redis.entity.Person;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.data.redis.core.ValueOperations;import org.springframework.stereotype.Repository;import javax.annotation.Resource;/** * create by jack 2017/10/11 */@Repositorypublic class PersonDao { /** * spring boot已为我们配置StringRedisTemplate,在此处可以直接注入 */ @Autowired private StringRedisTemplate stringRedisTemplate; /** * 可以使用@Resource注解指定stringRedisTemplate,可注入基于字符串的简单属性操作方法 */ @Resource(name="stringRedisTemplate") private ValueOperations<String,String> valOpsStr; /** * spring boot已为我们配置RedisTemplate,在此处可以直接注入 */ @Autowired private RedisTemplate<Object,Object> redisTemplate; /** * 可以使用@Resource注解指定redisTemplate,可注入基于对象的简单属性操作方法 */ @Resource(name = "redisTemplate") ValueOperations<Object,Object> valOps; /** * 通过set方法,存储字符串 */ public void stringRedisTemplateDemo(){ valOpsStr.set("xx","yy"); } /** * 通过set方法,存储对象 * @param person */ public void save(Person person){ valOps.set(person.getId(),person); } /** * 通过get方法,获得字符串 * @return */ public String getString(){ return valOpsStr.get("xx"); } /** * 通过get方法,获得对象 * @return */ public Person getPerson(){ return (Person) valOps.get("1"); }}
5,配置
Spring Boot为我们自动配置了RedisTemplate,而RedisTemplate使用的是JdkSerializationRedisSerializer,这个对我们演示Redis Client很不直观,因为JdkSerializationRedisSerializer使用二进制形式存储数据,在此我们将自己配置RedisTemplate并定义Serializer:
package com.jack.springboot10redis.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;import java.net.UnknownHostException;/** * create by jack 2017/10/11 */@Configurationpublic class RedisConfig { @Bean public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException{ RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); /** * 设置值value的序列化采用Jackson2JsonRedisSerializer */ template.setValueSerializer(jackson2JsonRedisSerializer); /** * 设置键key的序列化采用StringRedisSerializer */ template.setKeySerializer(new StringRedisSerializer()); template.afterPropertiesSet(); return template; }}
6,控制器
package com.jack.springboot10redis.controller;import com.jack.springboot10redis.dao.PersonDao;import com.jack.springboot10redis.entity.Person;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * create by jack 2017/10/11 */@RestController@RequestMapping("redis")public class RedisController { @Autowired private PersonDao personDao; /** * 演示设置字符及对象 */ @RequestMapping("/set") public void set(){ Person person = new Person("1","jack",22); personDao.save(person); personDao.stringRedisTemplateDemo(); } /** * 获得字符 * @return */ @RequestMapping("/getStr") public String getStr(){ return personDao.getString(); } /** * 获得对象 * @return */ @RequestMapping("/getPerson") public Person getPerson(){ return personDao.getPerson(); }}
7,运行
演示设置字符及对象,访问:http://localhost:9090/redis/set,此时查看Redis Client。对象存储如下:
字符存储如下:
演示获得字符,访问:http://localhost:9090/redis/getStr,页面显示如下:
演示获得对象,访问:http://localhost:9090/redis/getPerson,页面显示如下:
源码地址:https://github.com/wj903829182/SpringCloudTwo/tree/master/springboot10redis
- SpringBoot27-spingboot数据访问-NoSQL(Redis)
- SpringBoot26-spingboot数据访问-NoSQL(MongDB)
- SpringBoot25-spingboot数据访问-数据缓存Cache
- SpringBoot22-spingboot数据访问-Spring Data JPA
- SpringBoot23-spingboot数据访问-Spring Data REST
- SpringBoot24-spingboot数据访问-声明式事务
- springboot【11】数据访问之NoSQL数据库redis
- NOSQL----Redis(1)
- spingBoot
- NoSQL之Redis(二)---Java操作Redis存储自定义类型数据
- noSQL-redis学习(一)
- redis 一(nosql介绍)
- noSQL-redis学习(五) -- redis事务
- Spring Redis(2)数据访问
- NOSQL -- Redis
- NOSQL-Redis
- NoSQL-Redis
- Nosql学习之Redis资料(一)
- 指针
- Android之Fragment
- 【BZOJ】1875 [SDOI2009]HH去散步 DP+矩阵优化
- 【译】Scheduling Tasks
- arduino上采集的数据转化为odom
- SpringBoot27-spingboot数据访问-NoSQL(Redis)
- Hololens开发之环境搭建
- 最短路径——迪杰斯坷垃算法(有向图、单源最短路径)
- HDU5952 Counting Cliques 【搜索剪枝】
- 【模板】强连通分量
- 极1s刷Padavan改华硕[N14U N54U]固件
- 百度实时热点原理
- 【UVA 10397 Connect the Campus】& 最小生成树 & Kruskal
- 054 曲率的计算