Redis是一種nosql數據庫,以鍵值對<key,value>的形式存儲數據,其速度相比於MySQL之類的數據庫,相當於內存讀寫與硬盤讀寫的差別,所以常常用作緩存,用於少寫多讀的場景下,直接從緩存拿數據比從數據庫(數據庫要I/O操作)拿要快得多。Redis目前幾乎無處不在,大公司小公司都在用。
Spring cloud 2.x版本后默認Redis客戶端連接池類型使用的是lettuce,而Sping cloud 1.5.x使用的jedis。Lettuce 和 Jedis 的都是連接Redis Server的客戶端程序。Jedis在實現上是直連redis server,多線程環境下非線程安全,除非使用連接池,為每個Jedis實例增加物理連接;Lettuce基於Netty的連接實例(StatefulRedisConnection),可以在多個線程間並發訪問,且線程安全,滿足多線程環境下的並發訪問,同時它是可伸縮的設計,一個連接實例不夠的情況也可以按需增加連接實例。
1、 新建項目sc-redis,對應的pom.xml文件如下
<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>spring-cloud</groupId> <artifactId>sc-redis</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>sc-redis</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.RELEASE</version> </parent> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
2、 新建spring boot啟動類
package sc.redis; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class RedisApplication { public static void main(String[] args) { SpringApplication.run(RedisApplication.class, args); } }
3、 新建配置文件application.yml
server: port: 9004 spring: application: name: sc-redis redis: host: 127.0.0.1 password: port: 6379 timeout: 10000 # 連接超時時間(毫秒) database: 0 # Redis默認情況下有16個分片,這里配置具體使用的分片,默認是0 lettuce: pool: max-active: 8 # 連接池最大連接數(使用負值表示沒有限制) 默認 8 max-wait: -1 # 連接池最大阻塞等待時間(使用負值表示沒有限制) 默認 -1 max-idle: 8 # 連接池中的最大空閑連接 默認 8 min-idle: 0 # 連接池中的最小空閑連接 默認 0
備注:reids對用的所有配置項可以在以下類查看
org.springframework.boot.autoconfigure.data.redis.RedisProperties
4、 自定義Reids的Template
默認情況下的模板只能支持RedisTemplate<String, String>,也就是只能存入字符串,這在開發中是不友好的,所以自定義模板是很有必要的,當自定義了模板又想使用String存儲這時候就可以使用StringRedisTemplate的方式,它們之間並不沖突。
package sc.redis.config; import java.io.Serializable; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration @AutoConfigureAfter(RedisAutoConfiguration.class) public class RedisCacheAutoConfiguration { @Bean public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) { RedisTemplate<String, Serializable> template = new RedisTemplate<>(); //鍵的序列化方式 template.setKeySerializer(new StringRedisSerializer()); //值的序列化方式 template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); return template; } }
5、 新建一個模擬的Controller類
package sc.redis.config; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import sc.redis.model.User; @RestController public class UserCacheController { //@Autowired //private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate<String, Serializable> redisCacheTemplate; @GetMapping(value = "/cache/user/cacheUser") @ResponseBody public Map<String, Object> cacheUser() { Map<String, Object> result = new HashMap<String, Object>(); result.put("code", "000000"); result.put("msg", "success"); User u = new User(); u.setId(1L); u.setAge(23); u.setUserName("huangjinjin"); u.setPosition("cto"); result.put("body", u); redisCacheTemplate.opsForValue().set(String.valueOf(u.getId()), u); return result; } /** * 獲取緩存信息 * @param id * @return */ @GetMapping(value = "/cache/user/getCacheUser/{id}") @ResponseBody public Map<String, Object> getCacheUser(@PathVariable Long id) { Map<String, Object> result = new HashMap<String, Object>(); result.put("code", "000000"); result.put("msg", "success"); User u = (User) redisCacheTemplate.opsForValue().get(String.valueOf(1)); System.out.println(u.getUserName()); result.put("body", u); return result; } }
6、 啟動sc-redis項目,並驗證是否啟動成功
7、 使用postman訪問接口
(1) 存儲值到redis
http://127.0.0.1:9004/cache/user/cacheUser
(2) 從redis獲取存貯的值
http://127.0.0.1:9004/cache/user/getCacheUser/1
使用redis客戶端redis-cli查看是否把相關數據存貯到redis
下列的就是Redis其它類型所對應的操作方式:
opsForValue: 對應 String(字符串)
opsForZSet: 對應 ZSet(有序集合)
opsForHash: 對應 Hash(哈希)
opsForList: 對應 List(列表)
opsForSet: 對應 Set(集合)
opsForGeo: 對應 GEO(地理位置)