springboot2 配置redis,RedisTemplate,RedisCache(轉)


轉自https://blog.csdn.net/haveqing/article/details/86519992

spring boot2 集成Redis
https://www.cnblogs.com/antball/p/9239663.html

SpringBoot 2.X集成Redis(Lettuce)
https://blog.csdn.net/lx1309244704/article/details/80696235

SpringBoot2整合Redis緩存
https://blog.csdn.net/zsj777/article/details/80801824

SpringBoot2.0.3 Redis緩存 @Cacheable、@CacheEvict、@CachePut
https://blog.csdn.net/u010588262/article/details/81003493

史上最全面的Spring Boot Cache使用與整
https://www.cnblogs.com/yueshutong/p/9381540.html
————————————————

springboot1.5的版本redis客戶端默認是jedis,2.0以上版本默認是lettuce

本文采用lettuce,就是把application.yml配置文件里的jedis換成lettuce,

一、pom.xml

<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.urthink.upfs</groupId>
<artifactId>upfs-provider</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>upfs-provider</name>
<description>Upfs provider project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.SR2</spring-cloud.version>
</properties>

<dependencies>
<!--去掉springboot本身日志依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>

<!--log4j2-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 要用redis連接池 必須有pool依賴-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>

<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.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>

<dependency>
<groupId>com.urthink.upfs</groupId>
<artifactId>upfs-model</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>
二、application.yml

max-wait和timeout要寫單位,否則提示錯誤redis timeout Value '2000' is not a valid duration

spring:
redis:
# Redis數據庫索引(默認為0)
database: 10
# Redis服務器地址
host: 192.168.203.220
# Redis服務器連接端口
port: 6379
# Redis服務器連接密碼(默認為空)
password:
lettuce:
pool:
# 連接池最大連接數(使用負值表示沒有限制)
max-active: 200
# 連接池中的最大空閑連接
max-idle: 20
# 連接池中的最小空閑連接
min-idle: 10
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
max-wait: -1ms
# 連接超時時間(毫秒)默認是2000ms
timeout: 2000ms
三、RedisConfiguration.java

這個類主要是做一些配置,沒有這個類,下面的3個測試類也能跑通,

package com.urthink.upfs.provider.config;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method;
import java.net.UnknownHostException;
import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
* redis配置器
* 參考:RedisAutoConfiguration
* @author zhao
* @date 2019.1.16
*/
@Configuration
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {

//@Autowired
//private RedisConnectionFactory redisConnectionFactory;


@Bean //在沒有指定緩存Key的情況下,key生成策略
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append("#"+method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}

@Bean
public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {
//spring cache注解序列化配置
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getKeySerializer())) //key序列化方式
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer())) //value序列化方式
.disableCachingNullValues() //不緩存null值
.entryTtl(Duration.ofSeconds(60)); //默認緩存過期時間

// 設置一個初始化的緩存名稱set集合
Set<String> cacheNames = new HashSet<>();
cacheNames.add("user");

// 對每個緩存名稱應用不同的配置,自定義過期時間
Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
configMap.put("user", redisCacheConfiguration.entryTtl(Duration.ofSeconds(120)));

RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisTemplate.getConnectionFactory())
.cacheDefaults(redisCacheConfiguration)
.transactionAware()
.initialCacheNames(cacheNames) // 注意這兩句的調用順序,一定要先調用該方法設置初始化的緩存名,再初始化相關的配置
.withInitialCacheConfigurations(configMap)
.build();
return redisCacheManager;
}

// @Bean
// public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
// // 初始化緩存管理器,在這里我們可以緩存的整體過期時間等
// // 生成一個默認配置,通過config對象即可對緩存進行自定義配置
// //RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
// //config = config.entryTtl(Duration.ofSeconds(60)) // 設置緩存的默認過期時間,也是使用Duration設置
// // .disableCachingNullValues(); // 不緩存空值
// //RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory).cacheDefaults(config).build();
// RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory).build();
// return redisCacheManager;
// }


@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
// 配置redisTemplate
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
redisTemplate.setConnectionFactory(redisConnectionFactory);

//設置序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
// ObjectMapper om = new ObjectMapper();
// om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); //{"id":"1","name":"張三","age":18}
//// om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); //json數據帶類的名稱 //["com.urthink.upfs.model.entity.User",{"id":"1","name":"張三","age":18}]
// jackson2JsonRedisSerializer.setObjectMapper(om);
RedisSerializer stringSerializer = new StringRedisSerializer();

redisTemplate.setKeySerializer(stringSerializer); // key序列化
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // value序列化
redisTemplate.setHashKeySerializer(stringSerializer); // Hash key序列化
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); // Hash value序列化
redisTemplate.afterPropertiesSet();
return redisTemplate;
}

@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
三、測試類

1.User.java

package com.urthink.upfs.model.entity;

import lombok.Data;

import java.io.Serializable;

/**
* 實體類
*/
@Data
public class User implements Serializable {

private static final long serialVersionUID = 1L;

private String id;
private String name;
private int age;

}
2.UserService.java,spring boot cache注解

package com.urthink.upfs.provider.service;

import com.urthink.upfs.model.entity.User;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {

@Cacheable(value="user", key="#id") //user::0
public User getUser(String id) {
System.out.println(id+"進入實現類獲取數據!");
User user = new User();
user.setId(id);
user.setName("張三");
user.setAge(18);
return user;
}

@CacheEvict(value="user", key="#id", condition="#id!='1'")
public void deleteUser(String id) {
System.out.println(id+"進入實現類刪除數據!");
}

}
3.RedisService.java,redis 工具類,可以不用

package com.urthink.upfs.provider.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
* redis 工具類
*/
@Component
public class RedisService<HK, V> {

// 在構造器中獲取redisTemplate實例, key(not hashKey) 默認使用String類型
private RedisTemplate<String, V> redisTemplate;
// 在構造器中通過redisTemplate的工廠方法實例化操作對象
private HashOperations<String, HK, V> hashOperations;
private ListOperations<String, V> listOperations;
private ZSetOperations<String, V> zSetOperations;
private SetOperations<String, V> setOperations;
private ValueOperations<String, V> valueOperations;

// IDEA雖然報錯,但是依然可以注入成功, 實例化操作對象后就可以直接調用方法操作Redis數據庫
@Autowired
public RedisService(RedisTemplate<String, V> redisTemplate) {
this.redisTemplate = redisTemplate;
this.hashOperations = redisTemplate.opsForHash();
this.listOperations = redisTemplate.opsForList();
this.zSetOperations = redisTemplate.opsForZSet();
this.setOperations = redisTemplate.opsForSet();
this.valueOperations = redisTemplate.opsForValue();
}


public void hashPut(String key, HK hashKey, V value) {
hashOperations.put(key, hashKey, value);
}

public Map<HK, V> hashFindAll(String key) {
return hashOperations.entries(key);
}

public V hashGet(String key, HK hashKey) {
return hashOperations.get(key, hashKey);
}

public void hashRemove(String key, HK hashKey) {
hashOperations.delete(key, hashKey);
}

public Long listPush(String key, V value) {
return listOperations.rightPush(key, value);
}

public Long listUnshift(String key, V value) {
return listOperations.leftPush(key, value);
}

public List<V> listFindAll(String key) {
if (!redisTemplate.hasKey(key)) {
return null;
}
return listOperations.range(key, 0, listOperations.size(key));
}

public V listLPop(String key) {
return listOperations.leftPop(key);
}

public void setValue(String key, V value) {
valueOperations.set(key, value);
}

public void setValue(String key, V value, long timeout) {
ValueOperations<String, V> vo = redisTemplate.opsForValue();
vo.set(key, value, timeout, TimeUnit.MILLISECONDS);
}


public V getValue(String key) {
return valueOperations.get(key);
}

public void remove(String key) {
redisTemplate.delete(key);
}

public boolean expire(String key, long timeout, TimeUnit timeUnit) {
return redisTemplate.expire(key, timeout, timeUnit);
}
}
4.RedisTemplateTest.java

使用StringRedisTemplate,RedisTemplate<String, String>,RedisTemplate<Object, Object>都可以

package com.urthink.upfs.provider;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.TimeUnit;

/**
* redisTemplate測試
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTemplateTest {

@Autowired
//private StringRedisTemplate redisTemplate;
private RedisTemplate<String, String> redisTemplate;
//private RedisTemplate<Object, Object> redisTemplate;

@Test
public void testRedisTemplate(){
redisTemplate.opsForValue().set("test2","ddd",50, TimeUnit.SECONDS);
System.out.println(redisTemplate.opsForValue().get("test2"));
}
}
5.RedisCacheTest

package com.urthink.upfs.provider;


import com.urthink.upfs.model.entity.User;
import com.urthink.upfs.provider.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

/**
* SpringBoot緩存注解測試
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisCacheTest {

@Autowired
private StringRedisTemplate template;

@Autowired
private UserService userService;


@Test
public void getUser() {
for (int i = 0; i < 5; i++) {
User user = userService.getUser(String.valueOf(i));
System.out.println(user);
}
}

@Test
public void deleteUser() {
for (int i = 0; i < 5; i++) {
userService.deleteUser(String.valueOf(i));
}
}
}
6.RedisServiceTest.java

package com.urthink.upfs.provider;

import com.urthink.upfs.provider.service.RedisService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
* RedisService測試
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisServiceTest {
@Autowired
RedisService redisService;

@Test
public void setTest() {
redisService.setValue("key","hello");
}

@Test
public void getTest() {
System.out.println("getTest:"+ redisService.getValue("key"));
}

}

redis里的鍵值
user::1
{"id":"1","name":"張三","age":18}

鍵上為什么帶兩個冒號::?

RedisCache類createCacheKey方法
CacheKeyPrefix接口

   /**
     * Creates a default {@link CacheKeyPrefix} scheme that prefixes cache keys with {@code cacheName} followed by double
     * colons. A cache named {@code myCache} will prefix all cache keys with {@code myCache::}.
     *
     * @return the default {@link CacheKeyPrefix} scheme.
     */
    static CacheKeyPrefix simple() {
        return name -> name + "::";
    }
 

參考:

spring boot2 集成Redis
https://www.cnblogs.com/antball/p/9239663.html

SpringBoot 2.X集成Redis(Lettuce)
https://blog.csdn.net/lx1309244704/article/details/80696235

SpringBoot2整合Redis緩存
https://blog.csdn.net/zsj777/article/details/80801824

SpringBoot2.0.3 Redis緩存 @Cacheable、@CacheEvict、@CachePut
https://blog.csdn.net/u010588262/article/details/81003493

史上最全面的Spring Boot Cache使用與整
https://www.cnblogs.com/yueshutong/p/9381540.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM