Spring-boot教程(七)Redis缓存

https://blog.csdn.net/wangh92/article/details/79626969

一种是不用 properties/xml 配置文,用类来配置管理redis。另一种是写在yaml或者properties中

此文的项目基于springboot多模块,具体看教程四,本文都是在service模块操作...

一、简单配置使用

1、在service模块中加入

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

2、在你的类中注入

@Autowired
    private StringRedisTemplate stringRedisTemplate;

这个是专门的String类型的

或者

@Autowired
    private RedisTemplate redisTemplate;

然后保存key,取key,设置超时时间等等吧,其他类型的用法百度就行了,很多。

使用:redisTemplate.opsForValue().set("name","tom");
结果:redisTemplate.opsForValue().get("name")  输出结果为tom

3、在properties中加入基本的配置文件

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

这样就行了

二、类@Configeration配置

1、前言

springboot2.0版本集成redis与springboot1.x不一样,springboot1.x见:https://www.cnblogs.com/gdpuzxs/p/7222309.html

RedisCacheManager类初始化不再能以RedisTemplate为参数进行初始化,取而代之,官方(https://docs.spring.io/spring-data/redis/docs/2.0.5.RELEASE/reference/html/#new-in-2.0.0)给出了另一种初始化RedisCacheManager的方法:

RedisCacheManager在新版本中移除了该方法,所以不能再使用,若要使用则需要将spring-data-redis版本降低,1.6.0.RELEASE此方法是可用的,但是不推荐此方法,除非整体降低springboot的版本。

然后去查看spring2.0的官方文档,发下了如下描述:

2、pom文件添加

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

3、手动配置Redis

RedisConfig.java

@Configuration
@EnableCaching
@PropertySource(value = "classpath:application-service.properties")
public class RedisConfig  extends CachingConfigurerSupport{
	
	@Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.timeout}")
    private int timeout;

	@Primary
	@Bean
	public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
		RedisCacheManager redisCacheManager = RedisCacheManager.create(connectionFactory);
		return redisCacheManager;
	}
	
	@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;
    }
}

4、在service模块的application-service.properties中加入以下内容

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

5、基于注解的使用(与上一篇集成ehcache是一样的)

@Service
public class UserService implements IUserService {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

	@Autowired
	private IUserDb userDb;
	
	@Autowired
    private RedisTemplate redisTemplate;
	
	@Cacheable(key="'user_all'",value="userCache")
	@Override
	public List<User> getUsers() {
		LOGGER.info("查询数据库...");
		redisTemplate.opsForValue().set("name","tom");
		String str = (String) redisTemplate.opsForValue().get("name");
		LOGGER.info(str);
		return userDb.getUsers();
	}

	@CachePut(key="'user_'+#user.uid", value="userCache")
	@Override
	public void update(User user) {
		userDb.update(user);
	}

	@CacheEvict(key="'user_'+#uid", value="userCache")
	@Transactional
	@Override
	public void del(int id) {
		userDb.del(id);
	}

	@CacheEvict(key="'user'",value="userCache")
	@Override
	public void save(User user) {
		userDb.save(user);
	}

}

三、附录

1、注意点

如果之前集成了ehcache再集成redis,且也@Configuration ehcache的java文件,则需要在@bean cacheManager上加一个@Primary,不然会报错:No CacheResolver specified, and no unique bean of type CacheManager found

详情请看:https://blog.csdn.net/qq_35968129/article/details/73381227

猜你喜欢

转载自blog.csdn.net/wqc19920906/article/details/81588768