redis單機springboot連接使用

這裏是集羣其他配置

集羣環境https://blog.csdn.net/wasd986523/article/details/107002163

集羣代碼https://blog.csdn.net/wasd986523/article/details/107062807

單記安裝:https://blog.csdn.net/wasd986523/article/details/85331813

redis配置aof:https://blog.csdn.net/wasd986523/article/details/105244683

配置

<!-- springboot整合 redis -->
		<!-- Spring Boot Redis依賴 -->
		<!-- 注意:1.5版本的依賴和2.0的依賴不一樣,注意看哦 1.5我記得名字裏面應該沒有“data”, 2.0必須是“spring-boot-starter-data-redis” 
			這個纔行 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
			<!-- 1.5的版本默認採用的連接池技術是jedis 2.0以上版本默認連接池是lettuce, 在這裏採用jedis,所以需要排除lettuce的jar -->
			<exclusions>
				<exclusion>
					<groupId>redis.clients</groupId>
					<artifactId>jedis</artifactId>
				</exclusion>
				<exclusion>
					<groupId>io.lettuce</groupId>
					<artifactId>lettuce-core</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<!-- 添加jedis客戶端 -->
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
		</dependency>

		<!--spring2.0集成redis所需common-pool2 -->
		<!-- 必須加上,jedis依賴此 -->
		<!-- spring boot 2.0 的操作手冊有標註 大家可以去看看 地址是:https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/ -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-pool2</artifactId>
			<version>2.5.0</version>
		</dependency>

單機代碼配置

package com.jzlife.nurse.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
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.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

 
@Configuration
// 必須加,使配置生效
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {

    /**
     * Logger
     */
    private static final Logger lg = LoggerFactory.getLogger(RedisConfiguration.class);

    
    @Autowired
    private JedisConnectionFactory jedisConnectionFactory;

    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        //  設置自動key的生成規則,配置spring boot的註解,進行方法級別的緩存
        // 使用:進行分割,可以很多顯示出層級關係
        // 這裏其實就是new了一個KeyGenerator對象,只是這是lambda表達式的寫法,我感覺很好用,大家感興趣可以去了解下
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(":");
            sb.append(method.getName());
            for (Object obj : params) {
                sb.append(":" + String.valueOf(obj));
            }
            String rsToUse = String.valueOf(sb);
            lg.info("自動生成Redis Key -> [{}]", rsToUse);
            return rsToUse;
        };
    }

    @Bean
    @Override
    public CacheManager cacheManager() {
        // 初始化緩存管理器,在這裏我們可以緩存的整體過期時間什麼的,我這裏默認沒有配置
        lg.info("初始化 -> [{}]", "CacheManager RedisCacheManager Start");
        RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager
                .RedisCacheManagerBuilder
                .fromConnectionFactory(jedisConnectionFactory);
        return builder.build();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory ) {
        //設置序列化
        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);
        // 配置redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        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;
    }

    @Override
    @Bean
    public CacheErrorHandler errorHandler() {
        // 異常處理,當Redis發生異常時,打印日誌,但是程序正常走
        lg.info("初始化 -> [{}]", "Redis CacheErrorHandler");
        CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
            @Override
            public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
                lg.error("Redis occur handleCacheGetError:key -> [{}]", key, e);
            }

            @Override
            public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
                lg.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e);
            }

            @Override
            public void handleCacheEvictError(RuntimeException e, Cache cache, Object key)    {
                lg.error("Redis occur handleCacheEvictError:key -> [{}]", key, e);
            }

            @Override
            public void handleCacheClearError(RuntimeException e, Cache cache) {
                lg.error("Redis occur handleCacheClearError:", e);
            }
        };
        return cacheErrorHandler;
    }

    /**
     * 此內部類就是把yml的配置數據,進行讀取,創建JedisConnectionFactory和JedisPool,以供外部類初始化緩存管理器使用
     * 不瞭解的同學可以去看@ConfigurationProperties和@Value的作用
     *
     */
    @ConfigurationProperties
    class DataJedisProperties{
        @Value("${spring.redis.host}")
        private  String host;
        @Value("${spring.redis.password}")
        private  String password;
        @Value("${spring.redis.port}")
        private  int port;
        @Value("${spring.redis.timeout}")
        private  int timeout;
        @Value("${spring.redis.jedis.pool.max-idle}")
        private int maxIdle;
        @Value("${spring.redis.jedis.pool.max-wait}")
        private long maxWaitMillis;
        @Value("${spring.redis.database}")
        private int database;

        @Bean
        JedisConnectionFactory jedisConnectionFactory() {
            lg.info("Create JedisConnectionFactory successful");
            JedisConnectionFactory factory = new JedisConnectionFactory();
            factory.setHostName(host);
            factory.setPort(port);
            factory.setTimeout(timeout);
            factory.setPassword(password);
            factory.setDatabase(database);
            return factory;
        }
        @Bean
        public JedisPool redisPoolFactory() {
            lg.info("JedisPool init successful,host -> [{}];port -> [{}]", host, port);
            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            jedisPoolConfig.setMaxIdle(maxIdle);
            jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);

            JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
            return jedisPool;
        }
    }
    
    /**
     * //* @Cacheable : Spring在每次執行前都會檢查Cache中是否存在相同key的緩存元素,如果存在就不再執行該方法,而是直接從緩存中獲取結果進行返回,否則纔會執行並將返回結果存入指定的緩存中。
    //* @CacheEvict : 清除緩存。
    //* @CachePut : @CachePut也可以聲明一個方法支持緩存功能。使用@CachePut標註的方法在執行前不會去檢查緩存中是否存在之前執行過的結果,而是每次都會執行該方法,並將執行結果以鍵值對的形式存入指定的緩存中。

    @Autowired
    private UserDao userDao;


    @CacheEvict(value = CACHE_NAME_B, key = CACHE_KEY)
    @Override
    public int insert(User user) {
        return userDao.insert(user);
    }

    @CacheEvict(value = CACHE_NAME_B, key = "'user_' + #id") //這是清除緩存
    @Override
    public int deleteByPrimaryKey(String id) {
        Result result = new Result();
        return userDao.deleteByPrimaryKey(id);
    }

    @CacheEvict(value = CACHE_NAME_B, key = "'user_'+ #user.id")
    @Override
    public User updateByPrimaryKey(User user) {
        userDao.updateByPrimaryKey(user);
        return user;
    }

    @Cacheable(value = CACHE_NAME_B, key = "'user_'+ #id")
    @Override
    public User selectByPrimaryKey(String id) {
        return userDao.selectByPrimaryKey(id);
    }

    @Override
    public List<User> selectAllUser() {
        return userDao.selectAllUser();
    }

    @Cacheable(value = CACHE_NAME_B, key = "#userId+'_'+#userName")
    @Override
    public Result selectUserByAcount(Integer userId, String userName) {
        Result result = new Result();
        try {
            List<User> list = userDao.selectUserByAcount(userId, userName);
            if (list.size() == 0 || list.isEmpty()) {
                result.setRetCode(Result.RECODE_ERROR);
                result.setErrMsg("查找數據不存在");
                return result;
            }
            result.setData(list);
        } catch (Exception e) {
            result.setRetCode(Result.RECODE_ERROR);
            result.setErrMsg("方法執行出錯");
            logger.error("方法執行出錯", e);
            throw new RuntimeException(e);
        }
        return result;
    }
     */

} 

 

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