本文主要讲解Spring Boot整合Spring Data Redis。html
下载地址:https://pan.baidu.com/s/1V6m0lO5awVexoa8jQomL-gjava
<?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.yiidian</groupId> <artifactId>ch03_08_springboot_redis</artifactId> <version>1.0-SNAPSHOT</version> <!-- 导入springboot父工程. 注意:任何的SpringBoot工程都必须有的!!! --> <!-- 父工程的做用:锁定起步的依赖的版本号,并无真正到依赖 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.11.RELEASE</version> </parent> <dependencies> <!--web起步依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 配置使用 redis 启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> </dependencies> </project>
必须导入Spring Data Redis依赖!web
# redis配置 spring: redis: host: localhost # 默认localhost,须要远程服务器须要修改 port: 6379 # 默认6379,若是不一致须要修改 database: 0 # 表明链接的数据库索引,默认为0,
以上为Spring Boot的Redis配置redis
package com.yiidian.controller; import com.yiidian.domain.Customer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * 控制器 * 一点教程网 - www.yiidian.com */ @Controller public class CustomerController { @Autowired private RedisTemplate redisTemplate; /** * 往Redis存入对象 */ @RequestMapping("/put") @ResponseBody public String put(){ Customer customer = new Customer(); customer.setId(1); customer.setName("小明"); customer.setGender("男"); customer.setTelephone("132444455555"); //调用Redis的API存入数据 redisTemplate.opsForValue().set("customer",customer); return "success"; } /** * 从Redis取出对象 */ @RequestMapping("/get") @ResponseBody public Customer get(){ return (Customer)redisTemplate.opsForValue().get("customer"); } }
在Controller注入RedisTemplate模板对象,利用它来操做Redis数据库,这里写一个put方法,用于往Redis存入数据,一个get方法,从Redis获取数据。但须要注意的时候,若是操做的Pojo对象,该Pojo必须实现java.io.Serializable接口,以下:spring
/** * 实体类 * 一点教程网 - www.yiidian.com */ public class Customer implements Serializable{ private Integer id; private String name; private String gender; private String telephone;
先访问put方法,返回success表明存入数据成功!数据库
http://localhost:8080/putapache
再访问get方法,效果以下:springboot
原文地址:http://www.yiidian.com/springboot/springboot-redis.htmlapp
欢迎关注个人公众号:一点教程,得到高质量的IT学习资源和干货推送。 若是您对个人专题内容感兴趣,也能够关注个人网站:yiidian.com