您的位置:首页 > 数据库 > Redis

微服务,微架构[四]之springboot集成Redis缓存

2017-05-12 16:28 495 查看
一、介绍:

         spring data 框架提供了对Redis的操作,RedisTemplate 可以方便的操作redis缓存,极大的提高了开发效率,其实在这里  很多 插件都是spring 进行了封装例如:jdbcTemplate,mongTemplate等等工具类,我们只需要使用他提供的工具类即可,毕竟所有的开源都是经过大量的实践检验,个人认为比我们自己封装的要好,当然不外乎也有特别的高手或者爱好者自己封装。

         spring boot 在操作Redis数据库时,经常会用对象或者集合存储数据,大家都知道,我们在读写磁盘时需要将数据进行序列化和反序列的过程。由于springboot没有帮我们处理数据的序列化在保持到redis的时候需要手动处理序列化,在springboot官方文档中会有StringRedisTemplate操作数据,从名称上来看,就可以看出是专门处理字符串的实现类,其实StringRedisTemplate就是对RedisTemplate的是一个实现,要将对象存储那么就需要我们自己定义序列化类
 RedisObjectSerializer  就是我们自己定义的序列化和反序列类,专门用于保持对象进行序列化的实现

二、参数说明

配置数据库索引(默认为0)

spring.redis.database=0

配置服务器地址

spring.redis.host=localhost

配置服务器连接端口

spring.redis.port=6379

配置服务器连接密码(默认为空)

spring.redis.password=

配置连接池最大连接数(使用负值表示没有限制)

spring.redis.pool.max-active=8

配置连接池最大阻塞等待时间(使用负值表示没有限制)

spring.redis.pool.max-wait=-1

配置连接池中的最大空闲连接

spring.redis.pool.max-idle=8

配置连接池中的最小空闲连接

spring.redis.pool.min-idle=0

配置连接超时时间(毫秒)

spring.redis.timeout=0

三、代码演示

1、序列化反序列化类

/**
* @Title: RedisObjectSerializer.java
* @Package com.eshengtai.service
* Copyright: Copyright (c) 2015
* @author: abc
* @date: 2017年5月12日 下午3:46:18
*
*/
package com.eshengtai.service;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

public class RedisObjectSerializer implements RedisSerializer<Object> {

private Converter<Object, byte[]> serializer = new SerializingConverter();
private Converter<byte[], Object> deserializer = new DeserializingConverter();

static final byte[] EMPTY_ARRAY = new byte[0];

public Object deserialize(byte[] bytes) {
if (isEmpty(bytes)) {
return null;
}

try {
return deserializer.convert(bytes);
} catch (Exception ex) {
throw new SerializationException("Cannot deserialize", ex);
}
}

public byte[] serialize(Object object) {
if (object == null) {
return EMPTY_ARRAY;
}

try {
return serializer.convert(object);
} catch (Exception ex) {
return EMPTY_ARRAY;
}
}

private boolean isEmpty(byte[] data) {
return (data == null || data.length == 0);
}
}


2、RedisTemplate初始化

/**
* @Title: RedisConfig.java
* @Package com.eshengtai.service
* Copyright: Copyright (c) 2015
* @author: abc
* @date: 2017年5月12日 下午2:39:11
*
*/
package com.eshengtai.service;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}

@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new RedisObjectSerializer());
return template;
}

}


3、操作RedisTemplate存储数据

/**
* @Title: RedisUtil.java
* @Package com.eshengtai.redis
* Copyright: Copyright (c) 2015
* @author: abc
* @date: 2017年5月12日 上午11:36:15
*
*/
package com.eshengtai.service;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
* Redis基础操作类
*
* @ClassName: RedisUtil
* @date: 2017年5月12日 上午11:53:02
* @version: V1.0
*
*/
@Service
public class RedisOptionService {

@Autowired
private RedisTemplate<String, Object> redisTemplate;

/**
* 保存String数据
*
* @Title: setStr
* @param key
* @param value
*
*/
public void setStr(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}

public String getString(String key) {
return (String) redisTemplate.opsForValue().get(key);
}

/**
* 操作对象
*
* @Title: setObject
* @param key
* @param obj
*
*/
public void setObject(String key, Object obj) {
redisTemplate.opsForValue().set(key, obj);
}

public Object getObject(String key) {
return redisTemplate.opsForValue().get(key);
}

/**
* 保存List数据存储
*
* @param key
* @param listValue
* @return
*/
public void setList(String key, List<?> listValue) {
redisTemplate.opsForList().leftPush(key, listValue);
}

public List<?> getList(String key) {
return (List<?>) redisTemplate.opsForList().range(key, 0, -1);
}

/**
* 保存Map数据存储
*
* @param key
* @param mapValue
* @return
*/
public void setMap(String key, Map<Object, Object> mapValue) {
redisTemplate.opsForHash().putAll(key, mapValue);
}

public Map<Object, Object> getMap(String key) {
return redisTemplate.opsForHash().entries(key);
}

/**
* 保存Set数据存储
*
* @param key
* @param setValue
* @return
*/
public void setSet(String key, Set<?> setValue) {
redisTemplate.opsForSet().add(key, setValue);
}

public Set<?> getSet(String key) {
return (Set<?>) redisTemplate.opsForSet().members(key);
}

}


4、实体对象类

/**
* @Title: EShengTai.java
* @Package com.eshengtai.model
* Copyright: Copyright (c) 2015
* @author: abc
* @date: 2017年5月12日 下午1:33:23
*
*/
package com.eshengtai.model;

import java.io.Serializable;

public class EShengTai implements Serializable {
private String id;
private String name;

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;
}

}


5、接口调用演示

/**
* @Title: ESTController.java
* @Package com.eshengtai.controller
* Copyright: Copyright (c) 2015
* @author: abc
* @date: 2017年5月12日 上午10:56:03
*
*/
package com.eshengtai.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.eshengtai.model.EShengTai;
import com.eshengtai.service.RedisOptionService;

@RestController
@RequestMapping
public class ESTController {

@Autowired
private RedisOptionService redisOptionService;

/**
* 演示Redis工具类调用
*
* @Title: setString
* @return
*
*/
@RequestMapping("demo")
public String demo() {
String key = "springboot_redis";

// 演示 字符串操作
String eshengtai = "HelloWorld~";
System.out.println("-----------------字符串开始------------------");
redisOptionService.setStr(key, eshengtai);
System.out.println("-----------------保存完成,获取数据内容------------------");
System.out.println(redisOptionService.getString(key));
System.out.println("-----------------字符串结束------------------");

// 演示 对象操作
String keyObj = "springboot_redis_obj";
EShengTai est = new EShengTai();
est.setId("100");
est.setName("e生态");

System.out.println("-----------------对象开始------------------");
redisOptionService.setObject(keyObj, est);
System.out.println("-----------------保存完成,获取数据内容------------------");
EShengTai estCache = (EShengTai) redisOptionService.getObject(keyObj);
System.out.println(estCache.getId());
System.out.println(estCache.getName());
System.out.println("-----------------对象结束------------------");

// 演示 map操作

String keyMap = "springboot_redis_map";
Map map = new HashMap();
map.put("eshengtai", "eshengtai");
map.put("eshengtai100", "eshengtaiVal100");
System.out.println("-----------------Map开始------------------");
// redisOptionService.setMap(keyMap, map);
System.out.println("-----------------保存完成,获取数据内容------------------");
System.out.println(redisOptionService.getMap(keyMap));
System.out.println("-----------------Map结束------------------");

// 演示 list操作

String keylist = "springboot_redis_list";
List list = new ArrayList();
list.add(100);
list.add(2000);
System.out.println("-----------------List开始------------------");
// redisOptionService.setList(keylist, list);
System.out.println("-----------------保存完成,获取数据内容------------------");
System.out.println(redisOptionService.getList(keylist));
System.out.println("-----------------List结束------------------");

return "演示成功~";
}

}


6、资源文件配置

#tomcatport,projectName
server.port=80
server.context-path=/eshengtai

#1.redis config
spring.redis.database=0
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.pool.max-active=5
spring.redis.pool.max-wait=1000
spring.redis.pool.max-idle=2
spring.redis.pool.min-idle=0
spring.redis.timeout=5000


7、maven pom依赖

<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>spring-boot-redis</groupId>
<artifactId>spring-boot-redis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>

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

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

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

<!-- redis -->

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

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

</project>


以上就是集成Redis全部代码,测试结果图



欢迎大家多提建议,多评论
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring boot redis 缓存
相关文章推荐