本文主要講解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