springboot2.0整合redis案例
首先建立一個springboot專案。
新增pom配置:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> pom配置檔案內容為:
<?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.pangjh</groupId> <artifactId>springboot-redis</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot-redis</name> <description>redis快取</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </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-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> 建立redis配置檔案RedisConfig.java:
內容為:
package com.pangjh.conf; import java.util.concurrent.CountDownLatch; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; 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.StringRedisTemplate; import org.springframework.data.redis.listener.PatternTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; /** * redis配置 * @author pangjianhui * */ @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { @Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.addMessageListener(listenerAdapter, new PatternTopic("chat")); return container; } @Bean MessageListenerAdapter listenerAdapter(Receiver receiver) { return new MessageListenerAdapter(receiver, "receiveMessage"); } @Bean Receiver receiver(CountDownLatch latch) { return new Receiver(latch); } @Bean CountDownLatch latch() { return new CountDownLatch(1); } @Bean StringRedisTemplate template(RedisConnectionFactory connectionFactory) { return new StringRedisTemplate(connectionFactory); } public class Receiver { private CountDownLatch latch; @Autowired public Receiver(CountDownLatch latch) { this.latch = latch; } public void receiveMessage(String message) { latch.countDown(); } } } redis配置:
# REDIS # Redis資料庫索引(預設為0) spring.redis.database=0 # Redis伺服器地址 (預設為127.0.0.1) spring.redis.host=127.0.0.1 # Redis伺服器連線埠 (預設為6379) spring.redis.port=6379 # Redis伺服器連線密碼(預設為空) spring.redis.password= # 連線超時時間(毫秒) spring.redis.timeout=2000 以上操作基本完成了springboot2.0與redis的整合,下面我們測試使用:
通過程式碼方式使用redis 編寫controller:
package com.pangjh.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class PangjhController { @Autowired private StringRedisTemplate template; @RequestMapping("/setValue") public String setValue(){ if(!template.hasKey("shabao")){ template.opsForValue().append("shabao", "我是傻寶"); return "使用redis快取儲存資料成功"; }else{ template.delete("shabao"); return "key已存在"; } } @RequestMapping("/getValue") public String getValue(){ if(!template.hasKey("shabao")){ return "key不存在,請先儲存資料"; }else{ String shabao = template.opsForValue().get("shabao");//根據key獲取快取中的val return "獲取到快取中的資料:shabao="+shabao; } } } 啟動專案(注意這裡啟動專案需要確保redis服務的開啟狀態)
請求:http://localhost:8080/setValue
儲存資料到redis成功!
請求:http://localhost:8080/getValue,查詢資料
通過註解方式使用redis 編寫model:
package com.pangjh.model; import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = 1L; private String id; private String name; private int age; public User() { super(); } public User(String id, String name, int age) { super(); this.id = id; this.name = name; this.age = age; } 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; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } 編寫介面:
package com.pangjh.service; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import com.pangjh.model.User; public interface UserService { @Cacheable(value="users", key="'user_'+#id") User getUser(String id); @CacheEvict(value="users", key="'user_'+#id",condition="#id!=1") void deleteUser(String id); } 編寫介面實現類:
package com.pangjh.serviceImpl; import org.springframework.stereotype.Service; import com.pangjh.model.User; import com.pangjh.service.UserService; @Service public class UserServiceImpl implements UserService { @Override public User getUser(String id) { System.out.println(id+"進入實現類獲取資料!"); User user = new User(); user.setId(id); user.setName("香菇"); user.setAge(18); return user; } @Override public void deleteUser(String id) { System.out.println(id+"進入實現類刪除資料!"); } } 編寫controller:
package com.pangjh.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.pangjh.model.User; import com.pangjh.service.UserService; @RestController public class UserController { @Autowired private UserService userService; @RequestMapping("/getUser") public User getUser(){ User user = userService.getUser("xianggu"); return user; } @RequestMapping("/deleteUser") public String deleteUser(){ userService.deleteUser("xianggu"); return "執行了刪除"; } } 專案結構如下:
啟動專案
請求:http://localhost:8080/getUser
在快取的有效時間內,重複請求,後臺只會列印一次:
程式碼:https://github.com/pangjianhui1991/xianggu.git