Springboot集成Redis

第一步:直接导入Redis的依赖
springboot+redis+fastjson

<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>ccloud</groupId>
		<artifactId>cc1</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>bootTest</artifactId>
	<name>bootTest</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.38</version>
        </dependency>
	</dependencies>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>Dalston.SR1</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

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

第二步:配置RedisConfig
springboot 原生支持两种RedisTemplate, RedisTemplate<Object, Object>和StringRedisTemplate。
StringRedisTemplate 支持key,value都是string类型,也是我们常用的方式。(可以结合fastjson转换为对象)
RedisTemplate<Object, Object>,对象方式其实更适合业务使用,需要自己实现序列化方式,因为redis其实只支持String和byte[]存储。
操作对象springboot原生的是<Object,Object>,咱们可以改造为<String,Object>,方便使用。

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.StringRedisSerializer;

@Configuration
public class RedisConfig {
	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
		redisTemplate.setConnectionFactory(redisConnectionFactory);
		redisTemplate.setKeySerializer(new StringRedisSerializer());// 设置key的序列化器
		redisTemplate.setValueSerializer(new RedisConverter());// 设置值的序列化器
		return redisTemplate;
	}
}

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 RedisConverter implements RedisSerializer<Object> {
	private Converter<Object, byte[]> serializer = new SerializingConverter();// 序列化器
	private Converter<byte[], Object> deserializer = new DeserializingConverter();// 反序列化器

	@Override
	public byte[] serialize(Object o) throws SerializationException {// 将对象序列化成字节数组
		if (o == null)
			return new byte[0];
		try {
			return serializer.convert(o);
		} catch (Exception e) {
			e.printStackTrace();
			return new byte[0];
		}
	}

	@Override
	public Object deserialize(byte[] bytes) throws SerializationException {// 将字节数组反序列化成对象
		if (bytes == null || bytes.length == 0)
			return null;
		try {
			return deserializer.convert(bytes);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}

第三步:redis配置不能忘
application.properties配置如下

# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空) 
spring.redis.password=  
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=200
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=10 
# 连接池中的最小空闲连接  
spring.redis.pool.min-idle=0  
# 连接超时时间(毫秒)  
spring.redis.timeout=1000 

第四步:简单操作代码

import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DcController {

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	@Autowired
	StringRedisUtil stringRedisUtil;

	@GetMapping("/redisString")
	public String redis() {
		String key = "key001";
		// 简单String操作
		stringRedisTemplate.opsForValue().set("key", "value");
		stringRedisTemplate.opsForValue().get("key");
		// list操作 需要先PUSH才能创建LIST,直接SET 会报错找不到KEY
		stringRedisTemplate.opsForList().leftPush(key, "12");
		stringRedisTemplate.opsForList().leftPush(key, "13");
		stringRedisTemplate.opsForList().set(key, 2, "14");

		List<String> list = stringRedisTemplate.opsForList().range(key, 0, 2);
		for (String str : list) {
			System.out.println(str);
		}

		// hash操作
		String mapkey = "mapkey001";
		stringRedisTemplate.opsForHash().put(mapkey, "my01", "my01Value");
		stringRedisTemplate.opsForHash().put(mapkey, "my02", "my02Value");

		System.out.println(stringRedisTemplate.opsForHash().get(mapkey, "my01"));

		// set操作
		String setkey = "setkey001";
		stringRedisTemplate.opsForSet().add(setkey, "111", "222");
		Set<String> set = stringRedisTemplate.opsForSet().members(setkey);
		for (String str : set) {
			System.out.println(str);
		}
		return "1111";
	}

	@GetMapping("/redisObject")
	public String redisObject() {
		// value操作
		String key001 = "obj-key001";
		Apple a1 = new Apple(1, "Red", "500g");
		redisTemplate.opsForValue().set(key001, a1);
		Apple a2 = (Apple) redisTemplate.opsForValue().get(key001);
		System.out.println(a2.getColor());

		// list操作
		String key002 = "obj-key002";
		redisTemplate.opsForList().leftPush(key002, a1);
		redisTemplate.opsForList().leftPush(key002, a1);

		List<Object> list = redisTemplate.opsForList().range(key002, 0, 1);
		for (Object a : list) {
			System.out.println(((Apple) a).getColor());
		}
		return "22222";
	}

	@GetMapping("/redisObjectUtil")
	public String redisObjectUtil() {
		// value操作
		String key001 = "util-obj-key001";
		Apple a1 = new Apple(1, "Red", "500g");
		stringRedisUtil.set(key001, a1);
		Apple a2 = stringRedisUtil.get(key001, Apple.class);
		System.out.println(a2.getColor());

		return "22222";
	}
}

实现序列化的对象

import java.io.Serializable;

public class Apple implements Serializable{
	private static final long serialVersionUID = 1L;
	long id;
	String color;
	String weight;

	public Apple(long id, String color, String weight) {
		this.id = id;
		this.color = color;
		this.weight = weight;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

	public String getWeight() {
		return weight;
	}

	public void setWeight(String weight) {
		this.weight = weight;
	}

}

第四步:辅助工具类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;

@Component
public class StringRedisUtil {
	@Autowired
	StringRedisTemplate stringRedisTemplate;

	// ============================String=============================
	/**
	 * 普通缓存获取
	 * 
	 * @param key
	 *            键
	 * @return 值
	 */
	public String get(String key) {
		return key == null ? null : stringRedisTemplate.opsForValue().get(key);
	}

	/**
	 * 普通缓存放入
	 * 
	 * @param key
	 *            键
	 * @param value
	 *            值
	 * @return true成功 false失败
	 */
	public boolean set(String key, String value) {
		try {
			stringRedisTemplate.opsForValue().set(key, value);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 普通缓存获取
	 * 
	 * @param key
	 *            键
	 * @return 值
	 */
	public <T> T get(String key, Class<T> clazz) {
		String value = stringRedisTemplate.opsForValue().get(key);
		if (null != value) {
			return JSON.parseObject(value, clazz);
		}
		return null;
	}

	/**
	 * 普通缓存放入
	 * 
	 * @param key
	 *            键
	 * @param value
	 *            值
	 * @return true成功 false失败
	 */
	public <T> boolean set(String key, T value) {
		try {
			stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(value));
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值