springboot集成Redis

springboot集成Redis

前言

Redis是目前使用的非常广泛的内存数据库,相比memcached,它支持更加丰富的数据类型。本来简要介绍在springboot中使用redis的方法。

如何使用?

1、引入spring-boot-starter-redis

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

2、在application.properties增加Redis的配置

# 使用的数据库(0-15),默认为0
spring.redis.database=0  
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)
spring.redis.password=  

3、使用

@Autowired
private StringRedisTemplate stringRedisTemplate;

@RequestMapping(value = "/redis/{key}/{value}",method = RequestMethod.GET)
@ResponseBody
public String redisTest(@PathVariable String key,@PathVariable String value) {
    String redisValue = stringRedisTemplate.opsForValue().get(key);
    if (StringUtils.isEmpty(redisValue)) {
        stringRedisTemplate.opsForValue().set(key,value);
        return "操作成功!";
    }

    if (!redisValue.equals(value)) {
        stringRedisTemplate.opsForValue().set(key,value);
        return "操作成功!";
    }

    return String.format("redis中已存在[key=%s,value=%s]的数据!",key,value);
}

随便写的一个例子。

4、Sentinel模式配置
上面的是单机的一个配置,如果是主从,参考:

#redis配置
spring.redis.database=0
spring.redis.password=system
spring.redis.pool.max-idle=10
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=10
spring.redis.pool.max-wait=-1
spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=192.168.74.135:26379,192.168.74.136:26379

5、redis的全部配置:

# REDIS (RedisProperties)
spring.redis.cluster.max-redirects= # Maximum number of redirects to follow when executing commands across the cluster.
spring.redis.cluster.nodes= # Comma-separated list of "host:port" pairs to bootstrap from.
spring.redis.database=0 # Database index used by the connection factory.
spring.redis.url= # Connection URL, will override host, port and password (user will be ignored), e.g. redis://user:password@example.com:6379
spring.redis.host=localhost # Redis server host.
spring.redis.password= # Login password of the redis server.
spring.redis.ssl=false # Enable SSL support.
spring.redis.pool.max-active=8 # Max number of connections that can be allocated by the pool at a given time. Use a negative value for no limit.
spring.redis.pool.max-idle=8 # Max number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
spring.redis.pool.max-wait=-1 # Maximum amount of time (in milliseconds) a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely.
spring.redis.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive.
spring.redis.port=6379 # Redis server port.
spring.redis.sentinel.master= # Name of Redis server.
spring.redis.sentinel.nodes= # Comma-separated list of host:port pairs.
spring.redis.timeout=0 # Connection timeout in milliseconds.

6、使用redis自动缓存数据
可以把一些经常查询的数据放到redis缓存起来,不用每次都查询数据库。
上面是手动缓存到redis,这里介绍一下如何自动数据缓存到redis。

a.增加一个redis的配置类:

@Configuration
@EnableCaching
public class RedisConfig{

    @Bean
    public KeyGenerator redisKeyGenerator(){
        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;
    }
}

b.在需要缓存的service方法上加上注解:

@Cacheable(value = "userCache")
public TUser findById(String id) {
    return this.userRepository.findOne(id);
}

这样,就只有redis没有相应的Key的时候才会查询数据库。

我们看下redis:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Tk1qc5RU-1650942440047)(http://omh46px9n.bkt.clouddn.com/17-8-4/57679669.jpg)]

图中,redis的key就是你的参数。

Spring Boot 项目中集成 Redis 数据库,主要涉及以下几个步骤:引入依赖、配置 Redis 连接信息、使用 `RedisTemplate` 或 `StringRedisTemplate` 来操作 Redis 数据库。 ### 引入 Redis 依赖 在 `pom.xml` 文件中添加以下依赖以集成 Redis: ```xml <!-- Redis 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- 连接池依赖 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> ``` 这些依赖项将帮助封装与 Redis 交互的底层操作,并提供连接池功能以优化与 Redis 的连接管理,提高性能[^1]。 ### 配置 Redis 连接 在 `application.properties` 或 `application.yml` 文件中配置 Redis 的连接信息。以下是 `application.properties` 的示例配置: ```properties # Redis 配置 spring.redis.host=localhost spring.redis.port=6379 spring.redis.lettuce.pool.max-active=8 spring.redis.lettuce.pool.max-idle=8 spring.redis.lettuce.pool.min-idle=2 spring.redis.lettuce.pool.max-wait=2000ms ``` 如果使用 `application.yml`,则配置如下: ```yaml spring: redis: host: localhost port: 6379 lettuce: pool: max-active: 8 max-idle: 8 min-idle: 2 max-wait: 2000ms ``` 这些配置项用于指定 Redis 服务器的地址、端口以及连接池的相关参数。 ### 使用 RedisTemplate 操作 RedisSpring Boot 应用程序中,可以通过注入 `RedisTemplate` 来操作 Redis 数据库。下面是一个简单的示例,展示如何使用 `RedisTemplate` 设置和获取数据: ```java import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @Service public class RedisService { private final RedisTemplate<String, Object> redisTemplate; public RedisService(RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; } public void set(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object get(String key) { return redisTemplate.opsForValue().get(key); } } ``` 在这个示例中,`RedisTemplate` 被用来执行基本的键值对操作。`opsForValue()` 方法返回一个 `ValueOperations` 对象,可以用来设置和获取字符串类型的值。 ### 分布式会话场景(Redis-Session) 对于需要支持分布式会话的应用程序,可以利用 Spring Session 提供的功能,通过 Redis 来存储会话信息。这通常涉及到额外的配置和依赖项,但可以极大地简化跨多个服务实例的会话管理。 通过以上步骤,可以在 Spring Boot 项目中成功集成 Redis 数据库,并利用其提供的高性能数据访问能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值