用户综合分析系统: ------ springboot+redis实现二级缓存

导入一下依赖

<!--Spring Redis RedisAutoConfiguration-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>3.2.0</version>
</dependency>

新增以下类

ApplicationContextHolder在主包下

  • springboot后门 获取工厂容器
/**
* 该接⼝口为标记接⼝口,Spring⼯工⼚厂在初始化的时,会⾃自动注⼊入applicationContext
*/
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
	private static ApplicationContext applicationContext=null;
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws
	BeansException {
			this.applicationContext=applicationContext;
	}
	public static Object getBean(String beanName){
			return applicationContext.getBean(beanName);
	}
}

增加Application以下代码

package com.baizhi;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.web.client.RestTemplate;
@MapperScan(basePackages = "com.baizhi.dao")
@SpringBootApplication
public class UserApp01 {
    public static void main(String[] args) {
        SpringApplication.run(UserApp01.class,args);
    }
    //springmvc 自带的一个test客户端工具
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate redisTemplate=new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return redisTemplate;
    }
}

创建cache包 放入一下类

UserDefineRedisCache

package com.baizhi.cache;
import com.baizhi.ApplicationContextHolder;
import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class UserDefineRedisCache implements Cache {
    private static final Logger logger =
            LoggerFactory.getLogger(UserDefineRedisCache.class);
    //记录的是Mppper的Namespace
    private String id;
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private RedisTemplate redisTemplate= (RedisTemplate)
            ApplicationContextHolder.getBean("redisTemplate");
    public UserDefineRedisCache(String id){
        this.id=id;
    }
    @Override
    public String getId() {
        return id;
    }
    @Override
    public void putObject(Object key, Object value) {
        logger.debug("将查询结果缓存到Redis--cache.key"+key+"\tvalue"+value);
        ValueOperations opsForValue = redisTemplate.opsForValue();
        opsForValue.set(key, value, 30, TimeUnit.MINUTES);
    }
    @Override
    public Object getObject(Object key) {
        logger.debug("获取缓存结果"+key);
        ValueOperations opsForValue = redisTemplate.opsForValue();
        return opsForValue.get(key);
    }
    @Override
    public Object removeObject(Object key) {
        logger.debug("删除Redis中的Key:"+key);
        ValueOperations opsForValue = redisTemplate.opsForValue();
        Object value = opsForValue.get(key);
        redisTemplate.delete(key);
        return value;
    }
    @Override
    public void clear() {
        logger.debug("删除所有Redis中的缓存");
        redisTemplate.execute((RedisCallback) connection -> {
            connection.flushDb();
            return null;
        });
    }
    @Override
    public int getSize() {
        return 0;
    }
    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }
}

日志配置文件

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender" >
        <encoder>
            <pattern>%p %c#%M %d{yyyy-MM-dd HH:mm:ss} %m%n</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
              <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                 <fileNamePattern>logs/userLoginFile-%d{yyyyMMdd}.log</fileNamePattern>
                 <maxHistory>30</maxHistory>
              </rollingPolicy>
              <encoder>
                 <pattern>%p %c#%M %d{yyyy-MM-dd HH:mm:ss} %m%n</pattern>
        <charset>UTF-8</charset>
              </encoder>
    </appender>


    <!-- 控制台输出⽇日志级别 -->
    <root level="ERROR">
        <appender-ref ref="STDOUT" />
    </root>
    <logger name="org.springframework.jdbc" level="DEBUG" additivity="false">
        <appender-ref ref="STDOUT" />
    </logger>
    <logger name="com.baizhi.dao" level="TRACE" additivity="false">
        <appender-ref ref="STDOUT" />
    </logger>
    <logger name="com.baizhi.cache" level="DEBUG" additivity="false">
        <appender-ref ref="STDOUT" />
    </logger>
    <logger name="com.baizhi.datasource" level="DEBUG" additivity="false">
        <appender-ref ref="STDOUT" />
    </logger>
</configuration>

application.properties

spring.redis.host=Centos
spring.redis.port=6379
spring.redis.timeout=5s
spring.redis.lettuce.pool.max-active=10
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-wait=5ms
spring.redis.lettuce.pool.min-idle=1
spring.redis.lettuce.shutdown-timeout=100ms

文件结构

用户综合分析系统: ------ springboot+redis实现二级缓存_第1张图片

你可能感兴趣的:(Spring,Redis)