SpringBoot中Redis的基礎使用

基礎使用

首先引入依賴

 <!-- redis依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>

然後在application.yml的spring下增加redis配置:

代碼如下

 redis:
    # Redis數據庫索引(默認爲0)
    database: 0
    # Redis服務器地址
    host: 127.0.0.1
    # Redis服務器連接端口
    port: 6379
    password: '123456'
    jedis:
      pool:
        # 連接池最大連接數(使用負值表示沒有限制)
        max-active: 8
        # 連接池最大阻塞等待時間(使用負值表示沒有限制)
        max-wait: 1
        # 連接池中的最大空閒連接
        max-idle: 8
        # 連接池中的最小空閒連接
        min-idle: 0
    # 連接超時時間(毫秒)
    timeout: 5000

然後在根包下創建一個service的文件夾加,然後在裏面增加redis文件夾,redis文件夾裏編寫redis的基礎操作函數。

編寫IRedisService接口,編寫增刪改查函數,代碼如下:

import java.util.Map;
​
@Service
public interface IRedisService {
    /**
     * 加入元素
     * @param key
     * @param value
     */
    void  setValue(String key, Map<String, Object> value);
    /**
     * 加入元素
     * @param key
     * @param value
     */
    void  setValue(String key, String value);
    /**
     * 加入元素
     * @param key
     * @param value
     */
    void   setValue(String key, Object value);
    /**
     * 獲取元素
     * @param key
     */
    Object getMapValue(String key);
    /**
     * 獲取元素
     * @param key
     */
    Object getValue(String key);
​
}

編寫RedisServiceImpl實現,實現Redis的增刪改查。

package com.example.dynamicdb.service.redis;
​
import org.springframework.beans.factory.annotation.Autowired;
​
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
​
import java.util.Map;
import java.util.concurrent.TimeUnit;
​
@Service("RedisServiceImpl")
public class RedisServiceImpl implements IRedisService {
​
    public RedisServiceImpl(){}
​
    @Autowired
    private RedisTemplate redisTemplate;
​
​
    @Override
    public void setValue(String key, Map<String, Object> value) {
        ValueOperations<String, Object> vo = redisTemplate.opsForValue();
        vo.set(key, value);
        redisTemplate.expire(key, 1, TimeUnit.HOURS);
    }
​
    @Override
    public Object getValue(String key) {
        ValueOperations<String, String> vo = redisTemplate.opsForValue();
        return vo.get(key);
    }
​
    @Override
    public void setValue(String key, String value) {
        ValueOperations<String, Object> vo = redisTemplate.opsForValue();
        vo.set(key, value);
        redisTemplate.expire(key, 1, TimeUnit.HOURS);
    }
​
    @Override
    public void setValue(String key, Object value) {
        ValueOperations<String, Object> vo = redisTemplate.opsForValue();
        vo.set(key, value);
        redisTemplate.expire(key, 1, TimeUnit.HOURS);
    }
​
    @Override
    public Object getMapValue(String key) {
        ValueOperations<String, String> vo = redisTemplate.opsForValue();
        return vo.get(key);
    }
​
}

然後創建一個RedisController,編寫一個測試接口,如下:

@RestController
public class RedisController {
    @Resource(name = "RedisServiceImpl")//使用resource實例化對象,name是指定實例化的類,用於一個接口多個類繼承的情況
    private IRedisService iRedisService;
    @PostMapping(value = "/Redis/TestRedis")
    @ApiOperation(value = "redis測試接口", notes = "redis測試接口", httpMethod = "POST")
    public String TestRedis(){
        iRedisService.setValue("redis", "這是redis的測試數據");
        Object redis = iRedisService.getValue("redis");
        return redis.toString();
    }
}

redis緩存使用

首先創建一個config文件夾,然後創建一個RedisCacheConfig文件,代碼如下:

​
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.EnableCaching;
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.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
​
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
​
@EnableCaching
@Configuration
public class RedisCacheConfig {
​
​
    /**
     * 最新版,設置redis緩存過期時間
     */
​
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        return new RedisCacheManager(
                RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
                this.getRedisCacheConfigurationWithTtl( 60), // 默認策略,未配置的 key 會使用這個
                this.getRedisCacheConfigurationMap() // 指定 key 策略
        );
    }
​
    private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
        Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
        //SsoCache和BasicDataCache進行過期時間配置
        redisCacheConfigurationMap.put("messagCache", this.getRedisCacheConfigurationWithTtl(30 * 60));
​
        //自定義設置緩存時間
        redisCacheConfigurationMap.put("studentCache", this.getRedisCacheConfigurationWithTtl(60 ));
​
        return redisCacheConfigurationMap;
    }
​
    private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
        Jackson2JsonRedisSerializer<Object> 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);
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
                RedisSerializationContext
                        .SerializationPair
                        .fromSerializer(jackson2JsonRedisSerializer)
        ).entryTtl(Duration.ofSeconds(seconds));
​
        return redisCacheConfiguration;
    }
}

類名上有註解@Configuration,代表該類會在啓動時加入進bean集合。

然後在RedisController下編寫測試函數,如下:

 @Autowired
    private SqlSession sqlSession;
    @GetMapping(value = "/Redis/TestRedisCache")
    @ResponseBody
    @DS("db2")
    @Cacheable(cacheNames = "userCache", key = "#id")
    @ApiOperation(value="查詢單條記錄",notes = "查詢")
    public List<user> TestRedisCache(Integer id) {
        //讀取第二個數據庫的值
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<user> users = mapper.test();
        return users;
    }

使用@Cacheable註解緩存接口的返回值,cacheNames的值和key的值,組合起來成爲是緩存中的鍵值對的key值,如下圖。

----------------------------------------------------------------------------------------------------

到此,SpringBoot中Redis的基礎使用就已經介紹完了。

代碼已經傳到Github上了,歡迎大家下載。

Github地址:https://github.com/kiba518/dynamicdb

----------------------------------------------------------------------------------------------------

注:此文章爲原創,任何形式的轉載都請聯繫作者獲得授權並註明出處!
若您覺得這篇文章還不錯,請點擊下方的推薦】,非常感謝!

https://www.cnblogs.com/kiba/p/17480377.html

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章