Springboot 利用redis 作二级缓存

一、导入redis jar包

 <!--redis jar包-->
        <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>

启动类加上 @EnableCaching注解表示开启缓存功能

@SpringBootApplication
//开启缓存功能
@EnableCaching
public class ShiroApplication {

    public static void main(String[] args) {
        SpringApplication.run(ShiroApplication.class, args);
    }


}

 

二、redis配置

#redis配置

# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-idle=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=10000

三、Redis缓存配置类

package com.example.springboot.shiro.core.shiro;


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.cache.RedisCacheWriter;
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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method;
import java.time.Duration;


/**
 * Redis缓存配置类
 *
 * @author szekinwin
 */
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {


    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.timeout}")
    private int timeout;



    //缓存管理器
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {

        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1)); // 设置缓存有效期一小时
        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration).build();
    }


    @Bean

    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<Object,Object> redisTemplate = new RedisTemplate<Object, Object>();

        redisTemplate.setConnectionFactory(factory);



        //key序列化方式;(不然会出现乱码;),但是如果方法上有Long等非String类型的话,会报类型转换错误;

        //所以在没有自己定义key生成策略的时候,以下这个代码建议不要这么写,可以不配置或者自己实现ObjectRedisSerializer

        //或者JdkSerializationRedisSerializer序列化方式;

          RedisSerializer<String> redisSerializer = new StringRedisSerializer();//Long类型不可以会出现异常信息;

         redisTemplate.setKeySerializer(redisSerializer);

         redisTemplate.setHashKeySerializer(redisSerializer);
        //设置序列化Value的实例化对象
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return redisTemplate;

    }
    /**

     * 自定义key.

     * 此方法将会根据类名+方法名+所有参数的值生成唯一的一个key,即使@Cacheable中的value属性一样,key也会不一样。

     */



    public KeyGenerator keyGenerator() {

        System.out.println("RedisCacheConfig.keyGenerator()");

        return new KeyGenerator(){

            @Override

            public Object generate(Object o, Method method, Object... objects) {

                // This willgenerate a unique key of the class name, the method name

                //and allmethod parameters appended.

                StringBuilder sb = new StringBuilder();

                sb.append(o.getClass().getName());

                sb.append(method.getName());

                for (Object obj : objects) {

                    sb.append(obj.toString());

                }

                System.err.print("keyGenerator======>>>>>>" + sb.toString());

                return sb.toString();

            }

        };

    }
}

注: 如果报类型转换异常,请把热部署or 热加载关闭

四、redisMapper

package com.example.springboot.shiro.user.mapper;

import com.example.springboot.shiro.user.entity.Uuser;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;

/*
 * @Cacheable将查询结果缓存到redis中,(key="#p0")指定传入的第一个参数作为redis的key。

 * @CachePut,指定key,将更新的结果同步到redis中

 * @CacheEvict,指定key,删除缓存数据,allEntries=true,方法调用后将立即清除缓存
 */

@Mapper
@CacheConfig(cacheNames = "Uuser")
public interface RedisMapper {
    @CachePut(value = "usercache", key = "#p0")
    @Insert("insert into u_user(email,pswd) values(#{email},#{pswd})")
    int addUser(@Param("email")String email,@Param("pswd")String pswd);

    @Select("select * from u_user where email=#{email}")

    Uuser findById(@Param("email") String email);

    @CachePut(key = "#p0")
    @Update("update u_user set email=#{email} where id=#{id}")
    void updataById(@Param("id")String id,@Param("email")String email);

    //如果指定为 true,则方法调用后将立即清空所有缓存
    @CacheEvict(key ="#p0",allEntries=true)
    @Delete("delete from u_user where id=#{id}")
    int deleteById(@Param("id")int id);

}

注:关于缓存注解也可以标注在Service 类上,两者取其一

@Cacheable将查询结果缓存到redis中,(key="#p0")指定传入的第一个参数作为redis的key
@CachePut,指定key,将更新的结果同步到redis中
@CacheEvict,指定key,删除缓存数据,allEntries=true   (方法调用后将立即清除所有缓存),
@CacheConfig(cacheNames = "Uuser")  表示缓存信息放在Uuser里面

五、Service

  @Cacheable(value = "demoInfo") //缓存,这里没有指定key.
    public Uuser findById(String email) {
        System.err.println("LoginService.findById()=========从数据库中进行获取的....email=" + email);
        return redisMapper.findById(email);
    }
    
    @CacheEvict(value = "demoInfo")
    public void deleteFromCache(String email) {

        System.err.println("LoginService.delete().从缓存中删除.");

    }

注:@Cacheable(value ="demoInfo") 表示 缓存信息放在demoInfo里面

@CacheEvict(value="demoInfo") 表示清除demoInfo里面的缓存里面的信息

六、Controller 

 @RequestMapping(value = "redis",method = RequestMethod.POST)
    @ResponseBody
    public Uuser findById(String email) {

        return loginService.findById(email);
    }
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    @ResponseBody
    public String delete(String email){
        loginService.deleteFromCache(email);
        return "ok";
    }

七、测试

第一次:执行findById()方法

keyGenerator======>>>>>>com.example.springboot.shiro.user.service.LoginServicefindByIdadmin2018-07-29 15:31:19.165  INFO 10404 --- [nio-8080-exec-1] io.lettuce.core.EpollProvider            : Starting without optional epoll library
2018-07-29 15:31:19.165  INFO 10404 --- [nio-8080-exec-1] io.lettuce.core.KqueueProvider           : Starting without optional kqueue library
keyGenerator======>>>>>>com.example.springboot.shiro.user.service.LoginServicefindByIdadminLoginService.findById()=========从数据库中进行获取的....email=admin
2018-07-29 15:31:20,257 DEBUG DataSourceUtils:114 - Fetching JDBC Connection from DataSource

从上图可以看出,数据第一次是从数据库拿出,此时redis 缓存已生成,自定义key已生成

再次执行:执行findById()方法

keyGenerator======>>>>>>com.example.springboot.shiro.user.service.LoginServicefindByIdadmin2018-07-29 15:40:47,598 DEBUG RequestResponseBodyMethodProcessor:278 - Written [{"create_time":{"date":16,"day":4,"hours":11,"minutes":15,"month":5,"seconds":33,"time":1466046933000,"timezoneOffset":-480,"year":116},"email":"admin","id":1,"last_login_time":{"date":29,"day":0,"hours":12,"minutes":55,"month":6,"seconds":4,"time":1532840104000,"timezoneOffset":-480,"year":118},"nickname":"???","pswd":"","salt":"","status":1,"verificationCode":""}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@987455b]
2018-07-29 15:40:47,599 DEBUG DispatcherServlet:1076 - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2018-07-29 15:40:47,599 DEBUG DispatcherServlet:1000 - Successfully completed request

从日志中不难看出,第二次查询并没有到数据库中去查询,而是去缓存中调用。

转载于:https://www.cnblogs.com/wang-qiang/p/9432275.html

二级缓存的实现需要在Mybatis的配置文件中配置,具体步骤如下: 1.在SpringBoot的配置文件中,配置Mybatis的mapperLocations,typeAliasesPackage等属性。 2.在Mybatis的配置文件中,添加以下配置: ``` <settings> <setting name="cacheEnabled" value="true"/> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/> <setting name="defaultExecutorType" value="REUSE"/> <setting name="mapUnderscoreToCamelCase" value="true"/> <setting name="logImpl" value="LOG4J"/> <setting name="localCacheScope" value="SESSION"/> <setting name="jdbcTypeForNull" value="NULL"/> <setting name="defaultStatementTimeout" value="2500"/> <setting name="defaultFetchSize" value="1000"/> <setting name="safeRowBoundsEnabled" value="false"/> <setting name="callSettersOnNulls" value="false"/> <setting name="useColumnLabel" value="true"/> <setting name="returnInstanceForEmptyRow" value="false"/> <setting name="useGeneratedKeys" value="false"/> <setting name="autoMappingBehavior" value="PARTIAL"/> <setting name="autoMappingUnknownColumnBehavior" value="NONE"/> <setting name="cacheRefNamespace" value=""/> <setting name="defaultScriptingLanguage" value="XML"/> <setting name="defaultEnumTypeHandler" value="org.apache.ibatis.type.EnumOrdinalTypeHandler"/> <setting name="defaultNumericTypeHandler" value="org.apache.ibatis.type.BigDecimalTypeHandler"/> <setting name="defaultBooleanTypeHandler" value="org.apache.ibatis.type.BooleanTypeHandler"/> <setting name="defaultTypeHandler" value="org.apache.ibatis.type.ObjectTypeHandler"/> <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/> <setting name="defaultSqlProviderType" value="org.apache.ibatis.extensions.ibatisprovider.CustomSqlProvider"/> <setting name="excludeStatementTypes" value=""/> <setting name="mapEmptyStringsToNulls" value="false"/> <setting name="callAnyGetterOnMap" value="false"/> <setting name="returnInstanceForEmptyCollection" value="false"/> <setting name="multipleResultSetsEnabled" value="true"/> <setting name="useActualParamName" value="true"/> <setting name="logPrefix" value=""/> <setting name="configurationFactory" value=""/> <setting name="vfsImpl" value=""/> <setting name="usePrefixesInMapper" value="false"/> <setting name="useGeneratedKeysWithJdbc4GeneratedKeys" value="false"/> <setting name="sqlSessionFactoryBuilder" value=""/> <setting name="autoDelimitKeywords" value="false"/> <setting name="databaseIdProvider" value=""/> <setting name="defaultSqlProviderAnnotation" value=""/> <setting name="localCacheHashcode" value="false"/> <setting name="mailSession" value=""/> <setting name="useClassNameAsMapKey" value="true"/> <setting name="globalPropertiesRef" value=""/> <setting name="sqlResultSetHandlerFactory" value=""/> <setting name="databaseSchema" value=""/> <setting name="configurationProperties" value=""/> </settings> <typeAliases> <typeAlias alias="Student" type="com.csdn.entity.Student"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${mysql.driver}"/> <property name="url" value="${mysql.url}"/> <property name="username" value="${mysql.username}"/> <property name="password" value="${mysql.password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/csdn/mapper/StudentMapper.xml"/> </mappers> ``` 其中,设置cacheEnabled为true,开启缓存;设置localCacheScope为SESSION,开启二级缓存。 3.在mapper的.xml文件中,添加以下配置: ``` <select id="getStudent" resultMap="StudentResultMap" useCache="true" statementType="STATEMENT"> select * from student where id = #{id} </select> ``` 其中,useCache为true,开启缓存。 4.在需要使用二级缓存的实体类中,添加以下注解: ``` @CacheNamespace(eviction = FifoCache.class, flushInterval = 60000, size = 512, readWrite = true) ``` 其中,eviction表示策略,flushInterval表示刷新时间,size表示缓存最大值,readWrite表示是否支持读写。 以上就是SpringBoot+MybatisPlus+Redis实现二级缓存的步骤。希望能对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值