springboot快速启动(九)——整合Redis

一、步骤:
1、下载并安装Redis

windows 下载安装
Redis下载链接:https://github.com/MicrosoftArchive/redis/releases
简单直接.msi 一键安装版
或者下载Zip压缩包

Linux 下载安装 使用yum安装
更改yum源

mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup

下载新的CentOS-Base.repo 到/etc/yum.repos.d/

wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo

安装

yum install redis

启动

systemctl start redis.service

设置开机自启

systemctl enable redis.service

密码:

打开文件/etc/redis.conf,找到其中的# requirepass foobared,去掉前面的#,并把foobared改成你的密码。

2、项目pom文件加入依赖

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

3、application.properties中加入redis相关配置

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

4、配置类

@Configuration 
@AutoConfigureAfter(RedisAutoConfiguration.class) 
public class RedisConfig {
 /** * Logger */
  private static final Logger lg = LoggerFactory.getLogger(RedisConfig.class); 
  @Bean 
  public RedisTemplate redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) { 
  RedisTemplate template = new RedisTemplate<>(); 
  template.setKeySerializer(new StringRedisSerializer());
   template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setConnectionFactory(redisConnectionFactory);
    return template;
     } 
     }

5、注入实例

@Autowired private StringRedisTemplate stringRedisTemplate;

测试

  @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String testRedis() {
        stringRedisTemplate.opsForValue().set("姓名","小明");
        String str = stringRedisTemplate.opsForValue().get("姓名");
        System.out.println(str);
        return str;
    }

如果报connect 超时 Linux 关闭防火墙 或者 修改Redis配置文件 注释 bind 127.0.0.1 即解绑本机IP 并开启远程访问权限

发布了47 篇原创文章 · 获赞 30 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42083036/article/details/103141093