首页 > 数据库 >spring-boot 整合redis作为数据缓存

spring-boot 整合redis作为数据缓存

时间:2022-12-28 11:03:50浏览次数:44  
标签:return spring boot redis springframework import org public

 

添加依赖

<dependency>  
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>

Redis配置

package com.wisely.ij.config;  

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.RedisCacheManager;
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.Jackson2JsonRedisSerializer;

import java.lang.reflect.Method;


@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{

@Bean
public KeyGenerator wiselyKeyGenerator(){
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};

}

@Bean
public CacheManager cacheManager(
@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
return new RedisCacheManager(redisTemplate);
}

@Bean
public RedisTemplate<String, String> redisTemplate(
RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
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.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
# REDIS (RedisProperties)  
spring.redis.database= # database name
spring.redis.host=localhost # server host
spring.redis.password= # server password
spring.redis.port=6379 # connection port
spring.redis.pool.max-idle=8 # pool settings ...
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.sentinel.master= # name of Redis server
spring.redis.sentinel.nodes= # comma-separated list of host:port pairs

 

@Conditional(MyCondition.class)

 

这句代码可以标注在类上面,表示该类下面的所有@Bean都会启用配置

也可以标注在方法上面,只是对该方法启用配置

 

除了自己自定义Condition之外,Spring还提供了很多Condition给我们用

@ConditionalOnBean(仅仅在当前上下文中存在某个对象时,才会实例化一个Bean)
@ConditionalOnClass(某个class位于类路径上,才会实例化一个Bean)
@ConditionalOnExpression(当表达式为true的时候,才会实例化一个Bean)
@ConditionalOnMissingBean(仅仅在当前上下文中不存在某个对象时,才会实例化一个Bean)
@ConditionalOnMissingClass(某个class类路径上不存在的时候,才会实例化一个Bean)
@ConditionalOnNotWebApplication(不是web应用)

org.springframework.boot:spring-boot-autoconfigure:1.3.0.M2

package org.springframework.boot.autoconfigure.redis;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.redis.RedisProperties;
import org.springframework.boot.autoconfigure.redis.RedisProperties.Pool;
import org.springframework.boot.autoconfigure.redis.RedisProperties.Sentinel;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@ConditionalOnClass({JedisConnection.class, RedisOperations.class, Jedis.class})
@EnableConfigurationProperties
public class RedisAutoConfiguration {
public RedisAutoConfiguration() {
}

@Bean(
name = {"org.springframework.autoconfigure.redis.RedisProperties"}
)
@ConditionalOnMissingBean
public RedisProperties redisProperties() {
return new RedisProperties();
}

@Configuration
protected static class RedisConfiguration {
protected RedisConfiguration() {
}

@Bean
@ConditionalOnMissingBean(
name = {"redisTemplate"}
)
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}

@Bean
@ConditionalOnMissingBean({StringRedisTemplate.class})
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}

@Configuration
@ConditionalOnClass({GenericObjectPool.class})
protected static class RedisPooledConnectionConfiguration extends RedisAutoConfiguration.AbstractRedisConfiguration {
protected RedisPooledConnectionConfiguration() {
}

@Bean
@ConditionalOnMissingBean
public RedisConnectionFactory redisConnectionFactory() throws UnknownHostException {
return this.applyProperties(this.createJedisConnectionFactory());
}

private JedisConnectionFactory createJedisConnectionFactory() {
return this.properties.getPool() != null?
new JedisConnectionFactory(this.getSentinelConfig(), this.jedisPoolConfig()):
new JedisConnectionFactory(this.getSentinelConfig());
}

private JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig config = new JedisPoolConfig();
Pool props = this.properties.getPool();
config.setMaxTotal(props.getMaxActive());
config.setMaxIdle(props.getMaxIdle());
config.setMinIdle(props.getMinIdle());
config.setMaxWaitMillis((long)props.getMaxWait());
return config;
}
}

@Configuration
@ConditionalOnMissingClass({"org.apache.commons.pool2.impl.GenericObjectPool"})
protected static class RedisConnectionConfiguration extends RedisAutoConfiguration.AbstractRedisConfiguration {
protected RedisConnectionConfiguration() {
}

@Bean
@ConditionalOnMissingBean
public RedisConnectionFactory redisConnectionFactory() throws UnknownHostException {
return this.applyProperties(new JedisConnectionFactory(this.getSentinelConfig()));
}
}

protected abstract static class AbstractRedisConfiguration {
@Autowired
protected RedisProperties properties;
@Autowired(
required = false
)
private RedisSentinelConfiguration sentinelConfiguration;

protected AbstractRedisConfiguration() {
}

protected final JedisConnectionFactory applyProperties(JedisConnectionFactory factory) {
factory.setHostName(this.properties.getHost());
factory.setPort(this.properties.getPort());
if(this.properties.getPassword() != null) {
factory.setPassword(this.properties.getPassword());
}

factory.setDatabase(this.properties.getDatabase());
if(this.properties.getTimeout() > 0) {
factory.setTimeout(this.properties.getTimeout());
}

return factory;
}

protected final RedisSentinelConfiguration getSentinelConfig() {
if(this.sentinelConfiguration != null) {
return this.sentinelConfiguration;
} else {
Sentinel sentinelProperties = this.properties.getSentinel();
if(sentinelProperties != null) {
RedisSentinelConfiguration config = new RedisSentinelConfiguration();
config.master(sentinelProperties.getMaster());
config.setSentinels(this.createSentinels(sentinelProperties));
return config;
} else {
return null;
}
}
}

private List<RedisNode> createSentinels(Sentinel sentinel) {
ArrayList sentinels = new ArrayList();
String nodes = sentinel.getNodes();
String[] var4 = StringUtils.commaDelimitedListToStringArray(nodes);
int var5 = var4.length;

for(int var6 = 0; var6 < var5; ++var6) {
String node = var4[var6];

try {
String[] ex = StringUtils.split(node, ":");
Assert.state(ex.length == 2, "Must be defined as \'host:port\'");
sentinels.add(new RedisNode(ex[0], Integer.valueOf(ex[1]).intValue()));
} catch (RuntimeException var9) {
throw new IllegalStateException("Invalid redis sentinel property \'" + node + "\'", var9);
}
}

return sentinels;
}
}
}

 

package org.springframework.boot.autoconfigure.redis;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(
prefix = "spring.redis"
)
public class RedisProperties {
private int database = 0;
private String host = "localhost";
private String password;
private int port = 6379;
private int timeout;
private RedisProperties.Pool pool;
private RedisProperties.Sentinel sentinel;

public RedisProperties() {
}

public int getDatabase() {
return this.database;
}

public void setDatabase(int database) {
this.database = database;
}

public String getHost() {
return this.host;
}

public void setHost(String host) {
this.host = host;
}

public String getPassword() {
return this.password;
}

public void setPassword(String password) {
this.password = password;
}

public int getPort() {
return this.port;
}

public void setPort(int port) {
this.port = port;
}

public void setTimeout(int timeout) {
this.timeout = timeout;
}

public int getTimeout() {
return this.timeout;
}

public RedisProperties.Sentinel getSentinel() {
return this.sentinel;
}

public void setSentinel(RedisProperties.Sentinel sentinel) {
this.sentinel = sentinel;
}

public RedisProperties.Pool getPool() {
return this.pool;
}

public void setPool(RedisProperties.Pool pool) {
this.pool = pool;
}

public static class Sentinel {
private String master;
private String nodes;

public Sentinel() {
}

public String getMaster() {
return this.master;
}

public void setMaster(String master) {
this.master = master;
}

public String getNodes() {
return this.nodes;
}

public void setNodes(String nodes) {
this.nodes = nodes;
}
}

public static class Pool {
private int maxIdle = 8;
private int minIdle = 0;
private int maxActive = 8;
private int maxWait = -1;

public Pool() {
}

public int getMaxIdle() {
return this.maxIdle;
}

public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}

public int getMinIdle() {
return this.minIdle;
}

public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}

public int getMaxActive() {
return this.maxActive;
}

public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}

public int getMaxWait() {
return this.maxWait;
}

public void setMaxWait(int maxWait) {
this.maxWait = maxWait;
}
}
}

 

标签:return,spring,boot,redis,springframework,import,org,public
From: https://blog.51cto.com/u_15147537/5973892

相关文章

  • Windows下Redis中RedisQFork位置调整
     redis-server.exeredis.windows.conf使用上面命令启动redis服务的时候报了以下错误信息: ​​The Windows versionof Redis allocatesamemorymappedheap for ......
  • Redisson使用起来很方便,但是需要redis环境支持eval命令
     Redisson使用起来很方便,但是需要redis环境支持eval命令,否则一切都是悲剧,比如me.结果还是要用RedisCommands去写一套。例子就如下,获得一个RLock锁对象,然后tryLock和unlock......
  • org.springframework.web.bind.ServletRequestDataBinde
    org.springframework.validationClassDataBinder​​java.lang.Object​​org.springframework.validation.DataBinderAllImplementedInterfaces:​​PropertyEditorRe......
  • Spring中Bean的命名问题及ref和idref之间的区别
    一直在用Spring,其实对其了解甚少,刚去了解了一下Spring中Bean的命名问题以及ref和idref之间的区别,略作记录,以备后查。 Spring中Bean的命名1、每个Bean可以有一个id属性,并可......
  • spring事务理解
    分布式事务中是否可以有加锁解锁的逻辑?可以,但是不规范的话会有线程安全问题。下方逻辑:在解锁后,并发线程会再执行一遍锁里的逻辑,因为此时事务未提交,在隔离级别不是readun......
  • SpringBoot MultipartFile 上传文件null
    开发环境Springboot1.5.2使用方法,一开始直获取文件为null,不加required=false接口无法访问@PostMapping("/import")publicvoidimportTest(@RequestParam(v......
  • spring 基础2
    方便复习,转载于尚硅谷:https://www.yuque.com/tmfl/spring/of3mbz#3e4ec32a5、Spring的AOP5.1、AOP的相关概念在软件业,AOP为AspectOrientedProgramming的缩写,意为:面向......
  • Spring Cloud Alibaba之Nacos
    目录结构:一、SpringCloudAlibaba简介二、使用版本情况三、什么是Nacos?四、Nacos运行环境部署五、Nacos注册中心六、Nacos命名空间和分组......
  • Spring学习笔记 - 第三章 - AOP与Spring事务
    原文地址:Spring学习笔记-第三章-AOP与Spring事务Spring学习笔记全系列传送门:Spring学习笔记-第一章-IoC(控制反转)、IoC容器、Bean的实例化与生命周期、DI(依......
  • tomcat7运行springboot war包项目启动报错
    报错的log如下:2022-12-2801:11:22.701WARN39756---[localhost-startStop-1]ConfigServletWebServerApplicationContext:Exceptionencounteredduringcontext......