當前位置:首頁 » 硬碟大全 » springbootredis緩存原理
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

springbootredis緩存原理

發布時間: 2022-06-10 05:55:40

『壹』 怎麼看spring-bootspring-data-redis

spring boot對常用的資料庫支持外,對nosql 資料庫也進行了封裝自動化。

redis介紹

Redis是目前業界使用最廣泛的內存數據存儲。相比memcached,Redis支持更豐富的數據結構,例如hashes, lists,
sets等,同時支持數據持久化。除此之外,Redis還提供一些類資料庫的特性,比如事務,HA,主從庫。可以說Redis兼具了緩存系統和資料庫的一些特性,因此有著豐富的應用場景。本文介紹Redis在Spring
Boot中兩個典型的應用場景。

如何使用

1、引入 spring-boot-starter-redis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>

2、添加配置文件
# REDIS (RedisProperties)
# Redis資料庫索引(默認為0)
spring.redis.database=0
# Redis伺服器地址
spring.redis.host=192.168.0.58
# Redis伺服器連接埠
spring.redis.port=6379
# Redis伺服器連接密碼(默認為空)
spring.redis.password=
# 連接池最大連接數(使用負值表示沒有限制)
spring.redis.pool.max-active=8
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.pool.max-wait=-1
# 連接池中的最大空閑連接
spring.redis.pool.max-idle=8
# 連接池中的最小空閑連接
spring.redis.pool.min-idle=0
# 連接超時時間(毫秒)
spring.redis.timeout=0

3、添加cache的配置類
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{

@Bean
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();
}
};
}

@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
//設置緩存過期時間
//rcm.setDefaultExpiration(60);//秒
return rcm;
}

@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}

}

3、好了,接下來就可以直接使用了
@RunWith(SpringJUnit4ClassRunner.class)
@(Application.class)
public class TestRedis {

@Autowired
private StringRedisTemplate stringRedisTemplate;

@Autowired
private RedisTemplate redisTemplate;

@Test
public void test() throws Exception {
stringRedisTemplate.opsForValue().set("aaa", "111");
Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));
}

@Test
public void testObj() throws Exception {
User user=new User("[email protected]", "aa", "aa123456", "aa","123");
ValueOperations<String, User> operations=redisTemplate.opsForValue();
operations.set("com.neox", user);
operations.set("com.neo.f", user,1,TimeUnit.SECONDS);
Thread.sleep(1000);
//redisTemplate.delete("com.neo.f");
boolean exists=redisTemplate.hasKey("com.neo.f");
if(exists){
System.out.println("exists is true");
}else{
System.out.println("exists is false");
}
// Assert.assertEquals("aa", operations.get("com.neo.f").getUserName());
}
}

以上都是手動使用的方式,如何在查找資料庫的時候自動使用緩存呢,看下面;

4、自動根據方法生成緩存
@RequestMapping("/getUser")
@Cacheable(value="user-key")
public User getUser() {
User user=userRepository.findByUserName("aa");
System.out.println("若下面沒出現「無緩存的時候調用」字樣且能列印出數據表示測試成功");
return user;
}

其中value的值就是緩存到redis中的key

『貳』 springboot緩存怎麼來操作

1.在pom.xml中引入cache依賴,添加如下內容:

復制代碼
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
復制代碼
2.在Spring Boot主類中增加@EnableCaching註解開啟緩存功能,如下:

復制代碼
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
復制代碼
3.在數據訪問介面中,增加緩存配置註解,如:

復制代碼
@CacheConfig(cacheNames = "users")
public interface UserRepository extends JpaRepository<User, Long> {
@Cacheable
User findByName(String name);
}
復制代碼

SpringBoot支持很多種緩存方式:redis、guava、ehcahe、jcache等等。

『叄』 springboot怎麼使用redis

引入jedis就行了。
package com.vic.config;

import org.apache.log4j.Logger;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
*
* @author pieryon
*
*/
@Configuration
@EnableAutoConfiguration
@ConfigurationProperties(prefix = "spring.redis", locations = "classpath:application.properties")
public class RedisConfig {

private static Logger logger = Logger.getLogger(RedisConfig.class);

private String hostName;

private int port;

private String password;

private int timeout;

@Bean
public JedisPoolConfig getRedisConfig(){
JedisPoolConfig config = new JedisPoolConfig();
return config;
}

@Bean
public JedisPool getJedisPool(){
JedisPoolConfig config = getRedisConfig();
JedisPool pool = new JedisPool(config,hostName,port,timeout,password);
logger.info("init JredisPool ...");
return pool;
}

public String getHostName() {
return hostName;
}

public void setHostName(String hostName) {
this.hostName = hostName;
}

public int getPort() {
return port;
}

public void setPort(int port) {
this.port = port;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public int getTimeout() {
return timeout;
}

public void setTimeout(int timeout) {
this.timeout = timeout;
}
}

『肆』 springboot 中 RedisCacheManager rm = new RedisCacheManager(redisTemplate);我的項目沒這個構造

pom.xml 引入redis 開啟緩存

<!-- cache -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
application.properties 配置文件

# Redis資料庫索引(默認為0)spring.redis.database=0
# Redis伺服器地址spring.redis.host=localhost
# Redis伺服器連接埠spring.redis.port=6379
# Redis伺服器連接密碼(默認為空)spring.redis.password=
# 連接池最大連接數(使用負值表示沒有限制)
spring.redis.pool.max-active=8
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.pool.max-wait=-1
# 連接池中的最大空閑連接
spring.redis.pool.max-idle=8
# 連接池中的最小空閑連接
spring.redis.pool.min-idle=0
# 連接超時時間(毫秒)
spring.redis.timeout=0
添加cache的配置類

package www.ijava.com.configure;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.lang.reflect.Method;

import org.springframework.cache.CacheManager;
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.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;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{

@Bean
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();
}
};
}

@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
//設置緩存過期時間
//rcm.setDefaultExpiration(60);//秒
return rcm;
}

@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}

}
RedisService

package www.ijava.com.service;

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

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

/**
*/
@Service
public class RedisService {

@Autowired
private RedisTemplate redisTemplate;
/*
* //操作字元串
* redisTemplate.opsForValue();
//操作hash
redisTemplate.opsForHash();
//操作
redisTemplate.opsForList();
//操作
list redisTemplate.opsForSet();
//操作有序set
set redisTemplate.opsForZSet();

*/
/**
* 寫入緩存
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 寫入緩存設置時效時間
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 批量刪除對應的value
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}

/**
* 批量刪除key
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
/**
* 刪除對應的value
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判斷緩存中是否有對應的value
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 讀取緩存
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 哈希 添加
* @param key
* @param hashKey
* @param value
*/
public void hmSet(String key, Object hashKey, Object value){
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key,hashKey,value);
}

/**
* 哈希獲取數據
* @param key
* @param hashKey
* @return
*/
public Object hmGet(String key, Object hashKey){
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key,hashKey);
}

/**
* 列表添加
* @param k
* @param v
*/
public void lPush(String k,Object v){
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(k,v);
}

/**
* 列表獲取
* @param k
* @param l
* @param l1
* @return
*/
public List<Object> lRange(String k, long l, long l1){
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(k,l,l1);
}

/**
* 集合添加
* @param key
* @param value
*/
public void add(String key,Object value){
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add(key,value);
}

/**
* 集合獲取
* @param key
* @return
*/
public Set<Object> setMembers(String key){
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.members(key);
}

/**
* 有序集合添加
* @param key
* @param value
* @param scoure
*/
public void zAdd(String key,Object value,double scoure){
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add(key,value,scoure);
}

/**
* 有序集合獲取
* @param key
* @param scoure
* @param scoure1
* @return
*/
public Set<Object> rangeByScore(String key,double scoure,double scoure1){
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
return zset.rangeByScore(key, scoure, scoure1);
}
}

測試用的Controller

package www.ijava.com.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import www.ijava.com.service.RedisService;

@RestController
public class DemoController {

@Autowired
private RedisService redisService ;

@RequestMapping(value = "/test")
public String demoTest(){
boolean result = redisService.set("1","value22222");
Object object = redisService.get("1");
Object name = redisService.get("name");
System.out.println(object);
return result+"-------"+object+" ---"+name;
}

}
使用Redis-cli客戶端查看

『伍』 spring-boot-starter-data-redis 怎樣刪除緩存

你好!
使用手機自帶管理器打開c盤::cache文件夾是緩存目錄,建議大家定時清空。:所有temp文件夾
僅代表個人觀點,不喜勿噴,謝謝。

『陸』 SpringBoot集成Redis來實現緩存技術方案有哪些

首先可以在多台伺服器裝memcached,啟動時分別指定容量和埠 訪問時採用集群方式訪問,只需要spring配置文件裡面配置即可 value可以放任何對象,包括集合 每個鍵值的生命周期可以在放入時獨立設置 類庫可以用spymemcached 數據更新方式可以

『柒』 springboot 整合redis怎麼定時更新沒有sql數據

1,redis是一種內存性的數據存儲服務,所以它的速度要比mysql快。
2,redis只支持String,hashmap,set,sortedset等基本數據類型,但是不支持聯合查詢,所以它適合做緩存。
3,有時候緩存的數據量非常大,如果這個時候服務宕機了,且開啟了redis的持久化功能,重新啟動服務,數據基本上不會丟。
4,redis可以做內存共享,因為它可以被多個不同的客戶端連接。
5,做為mysql等資料庫的緩存,是把部分熱點數據先存儲到redis中,或第一次用的時候載入到redis中,下次再用的時候,直接從redis中取。
6,redis中的數據可以設置過期時間expire,如果這個數據在一定時間內沒有被延長這個時間,那個一定時間之後這個數據就會從redis清除。

『捌』 剛剛用spring boot 並用緩存資料庫redis ,哪裡有比較好的教程呢,菜鳥

首先可以在多台伺服器裝memcached,啟動時分別指定容量和埠
訪問時採用集群方式訪問,只需要spring配置文件裡面配置即可
value可以放任何對象,包括集合
每個鍵值的生命周期可以在放入時獨立設置
類庫可以用spymemcached

數據更新方式可以在後台的定時任務中執行

下面是spring mvc中配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

<bean id="memcachedClient" class="net.spy.memcached.spring.MemcachedClientFactoryBean">
<property name="servers" value="伺服器A:埠,伺服器B:埠,伺服器C:埠" />
<property name="protocol" value="BINARY" />
<property name="transcoder">
<bean class="net.spy.memcached.transcoders.SerializingTranscoder">
<property name="compressionThreshold" value="1024" />
</bean>
</property>
<property name="opTimeout" value="2000" />
<property name="timeoutExceptionThreshold" value="1998" />
<property name="locatorType" value="CONSISTENT" />
<property name="hashAlg">
<value type="net.spy.memcached.DefaultHashAlgorithm">KETAMA_HASH</value>
</property>
<property name="failureMode" value="Redistribute" />
<property name="useNagleAlgorithm" value="false" />
</bean>

『玖』 spring-boot-starter-data-redis能否獲取動態監控信息

1、redis功能是提供緩存服務的,spring與各中間件集成後一般也只提供中間件自己的功能。
2、cpu、內存等狀態監控並不是redis的功能,所以你不能通過它來查看。
3、你可以通過actuator來查看cpu、內存等信息。

『拾』 SpringBoot的學習清單匯總

Redis是目前業界使用最廣泛的內存數據存儲。相比memcached,Redis支持更豐富的數據結構,例如hashes, lists, sets等,同時支持數據持久化。除此之外,Redis還提供一些類資料庫的特性,比如事務,HA,主從庫。可以說Redis兼具了緩存系統和資料庫的一些特性,因此有著豐富的應用場景。本文介紹Redis在Spring Boot中兩個典型的應用場景。