Fork me on GitHub

Redis集成SpringBoot

简介

此案例中使用Centos7+redis+SpringBoot。
redis安装 https://www.cnblogs.com/xiaofengshan/p/15860447.html

添加依赖

 <!--redis需要依赖前-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.6.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <!--redis需要依赖后-->

配置文件

  • Yml配置
spring:    
  redis:
    #Redis服务器连接密码(默认为空)
#    username: root
#    password: 123QWEqwe
    host: 192.168.101.110
    port: 6379
    #连接超时时间(毫秒)
    timeout: 30000
    jedis:
      pool:
        # 连接池中的最小空闲连接
        min-idle: 2
        # 连接池中的最大空闲连接
        max-idle: 10
        # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1
        # 连接池最大连接数(使用负值表示没有限制)
        max-active: 1000
  • 代码配置
import java.lang.reflect.Method;
import java.time.Duration;

import org.springframework.beans.factory.annotation.Value;
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.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        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.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        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);
        // 配置序列化(解决乱码的问题),过期时间10秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(10))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

注意:外部访问redis的前提是把redis配置文件中的 protected-mode yes,改为 protected-mode no 这样redis才允许外部访问

测试案例

import com.yxkj.redisdemo.entity.TBICXX;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.List;

/**
 * @description:
 * @projectName:FoundationStudy
 * @see:com.yxkj.springbootdemo.dao
 * @author:zhuyang
 * @createTime:2021/10/31 21:45
 * @version:1.0 mysql
 */
@Repository
@Slf4j
public class TBAddressDao {
    @Resource
    private JdbcTemplate jdbcTemplate;


    /**
     * @Description:
     * @Author: zhuyang
     * @Date:  2022-02-04
     * @Param:
     * @return:
     * 根据方法对其返回结果进行缓存,下次请求时,如果缓存存在,则直接读取缓存数据返回;
     * 如果缓存不存在,则执行方法,并把返回的结果存入缓存中。一般用在查询方法上。
     * K值生成规则  value::key
     **/
    @Cacheable(value = "getId", key = "#id")
    public List<TBICXX> getId(String id){
        log.info("-----进入查询方法----");
        String sql="SELECT * FROM YXHIS..TBICXX WHERE CICID=?";
        List<TBICXX> collect = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(TBICXX.class),id);
        return collect;
    }

    /**
     * @Description:
     * @Author: zhuyang
     * @Date:  2022-02-04
     * @Param:
     * @return:
     * @CacheEvict是用来标注在需要清除缓存元素的方法或类上的。
     * 当标记在一个类上时表示其中所有的方法的执行都会触发缓存的清除操作。
     * @CacheEvict可以指定的属性有value、key、condition、allEntries和beforeInvocation。
     * 其中value、key和condition的语义与@Cacheable对应的属性类似。
     * 即value表示清除操作是发生在哪些Cache上的(对应Cache的名称);
     * key表示需要清除的是哪个key,如未指定则会使用默认策略生成的key;
     * condition表示清除操作发生的条件。下面我们来介绍一下新出现的两个属性allEntries和beforeInvocation。
     *
     * allEntries是boolean类型,表示是否需要清除缓存中的所有元素。默认为false,表示不需要。
     * 当指定了allEntries为true时,Spring Cache将忽略指定的key,
     * 而是根据指定的value属性进行匹配,清除所有value相同的元素
     * 有的时候我们需要Cache一下清除所有的元素,这比一个一个清除元素更有效率。
     **/
    @CacheEvict(value = "getId", allEntries=true,key = "#id")
    public Integer updateById(String username,String id) {
        log.info("-----进入更新方法----");
        String sql="UPDATE YXHIS..TBICXX SET CXM=? WHERE CICID=?";
        int update = jdbcTemplate.update(sql, username,id);
        return update;
    }

    /**
     * @Description:
     * @Author: zhuyang
     * @Date:  2022-02-04
     * @Param:
     * @return:
     * 使用该注解标志的方法,每次都会执行,并将结果存入指定的缓存中。
     * 其他方法可以直接从响应的缓存中读取缓存数据,
     * 而不需要再去查询数据库。一般用在新增方法上。
     * 一般不使用
     **/
    @CachePut(value = "getId")
    public Integer insertICXX(TBICXX tbicxx) throws Exception {
        log.info("-----进入增加方法----");
        String sql="insert into YXHIS..TBICXX(CICID,CXM,CXB,CBAH,CYLBX,IGRYH,BYXQ) VALUES(?,?,?,?,?,?,?)";
        int update = jdbcTemplate.update(sql, tbicxx.getCICID(), tbicxx.getCXM(), tbicxx.getCXB(), tbicxx.getCBAH(), tbicxx.getCYLBX(), tbicxx.getIGRYH(), tbicxx.getBYXQ());
        return update;
    }
}

Gitee地址

https://gitee.com/zhuayng/foundation-study/tree/develop/DataDemo/RedisDemo

posted @ 2022-02-02 16:17  晨度  阅读(65)  评论(0编辑  收藏  举报