Spring Boot中Redis的安装和解析与实战(附源码 超详细)

创作不易 觉得有帮助请点赞关注收藏~~~

一、Redis简介

Redis是一个开源的使用ANSIC语言编写,支持网络,可基于内存亦可持久化的日志型,key-value数据库,并提供多种语言的API。它支持多种数据类型。

但是在Redis在内存中存储数据,因此,存放在Redis中的数据不应该大于内存容量,否则回导致操作系统性能降低

二、安装Redis

1:下载Redis

https://github.com/MSOpenTech/redis/tags

2:启动Redis服务

使用redis-server-windows.conf命令行启动Redis服务 

 进入Redis解压目录 执行设置服务命令

redis-server--service-install redis.windows-service.conf--loglevel verbose 设置成windows下的服务

 常用的Redis服务命令如下

卸载服务 redis-server --service-uninstall
开启服务 redis-server --service-start
停止服务 redis-server --service-stop

3:操作测试Redis

启动服务后 可以使用如下命令创建一个数据库服务

redis-cli.exe-h 127.0.0.1-p 6379
set key value保存数据
get key 获取数据

三、Spring Boot整合Redis

Spring对Redis的支持是通过Spring Data Redis来实现的,提供了RedisTemplate和StringRedisTemplate两个模板来进行数据操作。 

序列化

当数据从存储到Redis时,键值都是通过Spring提供的Serializer序列化到数据的。

在Spring Boot应用中 只要引入spring-boot-starter-data-redis依赖就可以使用默认配置的Redis进行数据操作

实战在Spring Boot应用中使用StringRedisTemplate和RedisTmeplate模板访问操作Redis数据库

1:创建Spring Boot Web应用时记得引入上文所说依赖

2:application.properties不用配置

3:创建实体类 

创建名为com.ch.ch6_9.entity的包 并创建Student类 代码如下

package com.ch.ch6_9.entity;
import java.io.Serializable;
public class Student implements Serializable{
	private static final long serialVersionUID = 1L;
	private String sno;
	private String sname;
	private Integer sage;
	public Student() {
		super();
	}
	public Student(String sno, String sname, Integer sage) {
		super();
		this.sno = sno;
		this.sname = sname;
		this.sage = sage;
	}
	public String getSno() {
		return sno;
	}
	public void setSno(String sno) {
		this.sno = sno;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	public Integer getSage() {
		return sage;
	}
	public void setSage(Integer sage) {
		this.sage = sage;
	}
}

4:创建数据访问层

package com.ch.ch6_9.repository;
import java.util.List;
import javax.annotation.Resource;
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 com.ch.ch6_9.entity.Student;
@Repository
public class StudentRepository {
	@SuppressWarnings("unused")
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	@SuppressWarnings("unused")
	@Autowired
	private RedisTemplate<Object, Object> redisTemplate;
	/**
	 * 使用@Resource注解指定stringRedisTemplate,可注入基于字符串的简单属性操作方法
	 * ValueOperations<String, String> valueOpsStr = stringRedisTemplate.opsForValue();
	 */
	@Resource(name="stringRedisTemplate")
	ValueOperations<String, String> valueOpsStr;
	/**
	 * 使用@Resource注解指定redisTemplate,可注入基于对象的简单属性操作方法
	 * ValueOperations<Object, Object> valueOpsObject = redisTemplate.opsForValue();
	 */
	@Resource(name="redisTemplate")
	ValueOperations<Object, Object> valueOpsObject;
	/**
	 * 保存字符串到redis
	 */
	public void saveString(String key, String value) {
		valueOpsStr.set(key, value);
	}
	/**
	 * 保存对象到redis
	 */
	public void saveStudent(Student stu) {
		valueOpsObject.set(stu.getSno(), stu);
	}
	/**
	 * 保存List数据到redis
	 */
	public void saveMultiStudents(Object key, List<Student> stus) {
		valueOpsObject.set(key, stus);
	}
	/**
	 * 从redis中获得字符串数据
	 */
	public String getString(String key) {
		return valueOpsStr.get(key);
	}
	/**
	 * 从redis中获得对象数据
	 */
	public Object getObject(Object key) {
		return valueOpsObject.get(key);
	}
}

5:创建控制器层

package com.ch.ch6_9.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ch.ch6_9.entity.Student;
import com.ch.ch6_9.repository.StudentRepository;
@RestController
public class TestRedisController {
	@Autowired
	private StudentRepository studentRepository;
	@RequestMapping("/save")
	public void save() {
		studentRepository.saveString("uname", "陈恒");
		Student s1 = new Student("111","陈恒1",77);
		studentRepository.saveStudent(s1);
		Student s2 = new Student("222","陈恒2",88);
		Student s3 = new Student("333","陈恒3",99);
		List<Student>  stus = new ArrayList<Student>();
		stus.add(s2);
		stus.add(s3);
		studentRepository.saveMultiStudents("mutilStus",stus);
	}
	@RequestMapping("/getUname")
	@Cacheable(value = "myuname")
	public String getUname(String key) {
		System.out.println("测试缓存");
		return studentRepository.getString(key);
	}
	@RequestMapping("/getStudent")
	public Student getStudent(String key) {
		return (Student)studentRepository.getObject(key);
	}
	@SuppressWarnings("unchecked")
	@RequestMapping("/getMultiStus")
	public List<Student> getMultiStus(String key) {
		return (List<Student>)studentRepository.getObject(key);
	}
}

6:修改配置类

因为Redis默认使用序列化数据,这对使用Redis Client查看数据很不直观,所以我们自己配置并且定义Serializer

package com.ch.ch6_9;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
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 com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
@EnableCaching
@SpringBootApplication
public class Ch69Application {
	public static void main(String[] args) {
		SpringApplication.run(Ch69Application.class, args);
	}
	@Bean
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
		RedisTemplate<Object, Object> rTemplate = new RedisTemplate<Object, Object>();
		rTemplate.setConnectionFactory(redisConnectionFactory);
		@SuppressWarnings({ "unchecked", "rawtypes" })
		Jackson2JsonRedisSerializer<Object>  jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
		ObjectMapper om = new ObjectMapper();
		om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		jackson2JsonRedisSerializer.setObjectMapper(om);
		//设置值的序列化采用Jackson2JsonRedisSerializer
		rTemplate.setValueSerializer(jackson2JsonRedisSerializer);
		//设置键的序列化采用StringRedisSerializer
		rTemplate.setKeySerializer(new StringRedisSerializer());
		return rTemplate;
	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

showswoller

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值