springboot整个缓存_【springboot系列】springboot整合独立模块 redis 做缓存

项目github地址:https://github.com/5-Ason/aso...

具体可看 ./db/db-redis 和 ./db/db-cache 两个模块

// TODO 在整合redis之前需要先本地配置好redis环境,迟点有时间补一下linux下下载安装配置redis

本文主要实现的是对数据操作进行独立模块得整合,详情请看我的另一篇博文:

【技术杂谈】springcloud微服务之数据操作独立模块化

1、本篇目标

独立部署Redis非关系型数据库作为内存缓存模块,实现SpringBoot项目中依赖缓存模块进行缓存操作,并进行简单测试。

2、添加依赖

org.springframework.boot

spring-boot-starter-data-redis

org.springframework.boot

spring-boot-starter-cache

3、配置属性

因为我的项目使用的是springcloud分布式配置

所以配置文件在 ./config-server/config-repo/data-dev.yml,具体配置如下:

# ====================redis====================

redis:

# Redis服务器地址

host: ason-hostname

# Redis服务器连接端口

port: 6379

# Redis服务器连接密码(默认为空)

password:

# 连接超时时间(毫秒)

timeout: 0

# Redis数据库索引(默认为0)

database: 0

pool:

# 连接池最大连接数(使用负值表示没有限制)

max-active: 8

# 连接池最大阻塞等待时间(使用负值表示没有限制)

max-wait: -1

# 连接池中的最大空闲连接

max-idle: 8

# 连接池中的最小空闲连接

min-idle: 0

4、RedisConf配置

package com.ason;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.beans.factory.annotation.Value;

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.jedis.JedisConnectionFactory;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.serializer.StringRedisSerializer;

import redis.clients.jedis.JedisPoolConfig;

/**

* Created by Ason on 2017-09-23.

*/

@Configuration

public class RedisConf {

private static final Log log = LogFactory.getLog(RedisConf.class);

@Value("${redis.host}")

private String host; // Redis服务器地址

@Value("${redis.port}")

private int port; // Redis服务器连接端口

@Value("${redis.password}")

private String password; // Redis服务器连接密码(默认为空)

@Value("${redis.timeout}")

private int timeout; // 连接超时时间(毫秒)

@Value("${redis.database}")

private int database; // 连接超时时间(毫秒)

@Value("${redis.pool.max-active}")

private int maxTotal; // 连接池最大连接数(使用负值表示没有限制)

@Value("${redis.pool.max-wait}")

private int maxWaitMillis; // 连接池最大阻塞等待时间(使用负值表示没有限制)

@Value("${redis.pool.max-idle}")

private int maxIdle; // 连接池中的最大空闲连接

@Value("${redis.pool.min-idle}")

private int minIdle; // 连接池中的最小空闲连接

/**

* 配置JedisPoolConfig

* @return JedisPoolConfig实体

*/

@Bean(name = "jedisPoolConfig")

public JedisPoolConfig jedisPoolConfig() {

log.info("初始化JedisPoolConfig");

JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();

jedisPoolConfig.setMaxTotal(this.maxTotal); // 连接池最大连接数(使用负值表示没有限制)

jedisPoolConfig.setMaxWaitMillis(this.maxWaitMillis); // 连接池最大阻塞等待时间(使用负值表示没有限制)

jedisPoolConfig.setMaxIdle(this.maxIdle); // 连接池中的最大空闲连接

jedisPoolConfig.setMinIdle(this.minIdle); // 连接池中的最小空闲连接

// jedisPoolConfig.setTestOnBorrow(true);

// jedisPoolConfig.setTestOnCreate(true);

// jedisPoolConfig.setTestWhileIdle(true);

return jedisPoolConfig;

}

/**

* 实例化 RedisConnectionFactory 对象

* @param poolConfig

* @return

*/

@Bean(name = "jedisConnectionFactory")

public RedisConnectionFactory jedisConnectionFactory(@Qualifier(value = "jedisPoolConfig") JedisPoolConfig poolConfig) {

log.info("初始化RedisConnectionFactory");

JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig);

jedisConnectionFactory.setHostName(this.host);

jedisConnectionFactory.setPort(this.port);

jedisConnectionFactory.setDatabase(this.database);

return jedisConnectionFactory;

}

/**

* 实例化 RedisTemplate 对象

* @return

*/

@Bean(name = "redisTemplate")

public RedisTemplate functionDomainRedisTemplate(@Qualifier(value = "jedisConnectionFactory") RedisConnectionFactory factory) {

log.info("初始化RedisTemplate");

RedisTemplate redisTemplate = new RedisTemplate<>();

redisTemplate.setConnectionFactory(factory);

redisTemplate.setKeySerializer(new StringRedisSerializer());

redisTemplate.setHashKeySerializer(new StringRedisSerializer());

redisTemplate.setHashValueSerializer(new EntityRedisSerializer());

redisTemplate.setValueSerializer(new EntityRedisSerializer());

redisTemplate.afterPropertiesSet();

redisTemplate.setEnableTransactionSupport(true);

return redisTemplate;

}

}

RedisConf中涉及到的序列化相关的类

EntityRedisSerializer

package com.ason;

import org.springframework.data.redis.serializer.RedisSerializer;

import org.springframework.data.redis.serializer.SerializationException;

/**

* 自定义Redis序列化

* Created by Ason on 2017-09-23.

*/

public class EntityRedisSerializer implements RedisSerializer {

@Override

public byte[] serialize(Object t) throws SerializationException {

if (t == null) {

return new byte[0];

}

return SerializeUtil.serialize(t);

}

@Override

public Object deserialize(byte[] bytes) throws SerializationException {

if (bytes == null || bytes.length == 0) {

return null;

}

return SerializeUtil.unserialize(bytes);

}

}

SerializeUtil

package com.ason;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

/**

* 定义序列化

* Created by Ason on 2017-09-23.

*/

public class SerializeUtil {

public static byte[] serialize(Object object) {

ObjectOutputStream oos = null;

ByteArrayOutputStream baos = null;

try {

// 序列化

baos = new ByteArrayOutputStream();

oos = new ObjectOutputStream(baos);

oos.writeObject(object);

byte[] bytes = baos.toByteArray();

return bytes;

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

public static Object unserialize(byte[] bytes) {

ByteArrayInputStream bais = null;

try {

// 反序列化

bais = new ByteArrayInputStream(bytes);

ObjectInputStream ois = new ObjectInputStream(bais);

return ois.readObject();

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

}

5、RedisCacheConf配置

package com.ason;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.annotation.Autowired;

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.core.RedisTemplate;

import java.lang.reflect.Method;

/**

* Created by Ason on 2017/9/25.

* 这里实现CachingConfigurerSupport主要是方便使用自定义keyGenerator

*/

@Configuration

@EnableCaching // 启用缓存

public class RedisCacheConf extends CachingConfigurerSupport {

@Autowired

private RedisTemplate redisTemplate;

private static final Log log = LogFactory.getLog(RedisConf.class);

/**

* 配置redis缓存管理对象

* @return

*/

@Bean(name = "cacheManager")

public CacheManager cacheManager() {

log.info("初始化CacheManager");

RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);

// Map expires = new HashMap<>();

// expires.put("cache:user", 36000L);

// cacheManager.setExpires(expires);

//设置缓存过期时间

//cacheManager.setDefaultExpiration(10000);

return cacheManager;

}

/**

* 生成key的策略

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

* @return

*/

@Bean

public KeyGenerator keyGenerator() {

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();

}

};

}

}

6、具体使用

因为是将redis的配置单独作为一个模块db-redis,CacheManager的配置模块db-cache依赖db-redis:

com.ason

db-redis

0.0.1-SNAPSHOT

所以我的rms-service微服务想进行缓存的操作,需依赖db-cache模块:

com.ason

db-cache

0.0.1-SNAPSHOT

同时,还需要读取redis配置的属性,上面我的配置是放在 ./config-server/config-repo/data-dev.yml 下,所以在rms-service微服务下的 bootstrap.yml 配置文件中,需要指定配置中心服务的地址以及配置文件的name和profile:

spring:

# 配置中心服务的地址

cloud:

config:

name: data

profile: ${spring.profiles.active} # 要读取的配置文件profile属性

# uri: http://127.0.0.1:7001

#label: ${spring.profiles.active}

discovery:

enabled: true # 默认false,设为true表示使用注册中心中的configserver配置而不自己配置configserver的uri

serviceId: config-server

profiles:

active: dev

接下来,即可使用缓存相关的注解在 rms-service 微服务下使用缓存,在 RmsUserController(仅为测试,实际开发中根据需求做调整) 添加:

/**

* 查询单个用户

*/

@Cacheable(value = "usercache", key = "#account")

@PostMapping(value = "/account", produces = "application/json;charset=UTF-8")

public String findUserByAccout(@RequestParam("account") String account) throws Exception {

return ResultBody.success(rmsUserService.selectUserByAccout(account));

}

接下来,再去redis看一下,发现11@qq.com已作为key保存起来了:

7、注意事项

有些情形下注解式缓存会不起作用的(本人第一次整合测试遇到的坑):

同一个bean内部方法调用、子类调用父类中有缓存注解的方法等。

至此,已完成 springboot 整合独立模块 redis 做缓存

详情请看github地址:https://github.com/5-Ason/aso...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值