spring boot整合redis中间件与热部署实现

热部署

每次写完程序后都需要重启服务器,需要大量的时间,spring boot提供了一款工具devtools帮助实现热部署。

		
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-devtools</artifactId>
     <optional>true</optional> <!-- 可选 -->
 </dependency>

在这里插入图片描述

导入插件的以来后每次点击 ---->构建------>构建项目就可以了,相比重启要快的多。

Redis

spring boot整合redis最常用的有三个工具库Jedis,Redisson,Lettuce

共同点:都提供了基于 Redis 操作的 Java API,只是封装程度,具体实现稍有不同。

不同点:

  1. Jedis是 Redis 的 Java 实现的客户端。支持基本的数据类型如:String、Hash、List、Set、Sorted Set。
    特点:使用阻塞的 I/O,方法调用同步,程序流需要等到 socket 处理完 I/O 才能执行,不支持异步操作。Jedis 客户端实例不是线程安全的,需要通过连接池来使用 Jedis。

  2. Redisson
    优点点:分布式锁,分布式集合,可通过 Redis 支持延迟队列。

  3. Lettuce
    用于线程安全同步,异步和响应使用,支持集群,Sentinel,管道和编码器。
    基于 Netty 框架的事件驱动的通信层,其方法调用是异步的。Lettuce 的 API 是线程安全的,所以可以操作单个 Lettuce 连接来完成各种操作。

Jedis
  • 引入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>


<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.1.0</version>
</dependency>

  • 配置文件

# Redis服务器地址
spring.data.redis.host=192.168.223.128
# Redis服务器连接端口
spring.data.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.data.redis.password=root

注意时spring.data.redis而不是spring.redis后者已经舍弃了。

通过jedis连接redis:

import redis.clients.jedis.Jedis;

public class RedisConect {

    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.223.128",6379);
        //配置连接密码
        jedis.auth("root");
        String csvfile = jedis.get("csvfile");
        System.out.println(csvfile);
        jedis.close();
    }
}

spring boot 联合jedis连接redis:

//装配参数
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "spring.data.redis")
@Data
public class RedisConfig {
    private String host;
    private int port;
    private String password;
}


//创建jedis
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

@Service
public class JedisService {
    @Autowired RedisConfig redisConfig;



    public Jedis defaultJedis(){
        Jedis jedis = new Jedis(redisConfig.getHost(),redisConfig.getPort());
        jedis.auth(redisConfig.getPassword());
        return jedis;
    }
}


//测试
    @Test
    void One(){
        jedisService.defaultJedis().set("one","word");
        String one = jedisService.defaultJedis().get("one");
        System.out.println(one);
    }

在这里插入图片描述

RedisTemplate

装配参数除了上面@ConfigurationProperties的方法还有PropertySource方法:


@Configuration
@PropertySource("classpath:redis.properties")
public class RedisConfig {
 
    @Value("${redis.hostName}")
    private String hostName;
 
    @Value("${redis.password}")
    private String password;
 
    @Value("${redis.port}")

}

RedisTemplate是spring自带模板,需要配置一些参数:

package com.example.JedsFactory;

import com.example.RedisConfig.RedisConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

@Configuration
@PropertySource("classpath:redis.properties")
public class JedisFactory {

        @Value("${spring.data.redis.host}")
        private String host;

        @Value("${spring.data.redis.password}")
        private String password;

        @Value("${spring.data.redis.port}")
        private Integer port;

        @Bean
        public JedisConnectionFactory JedisConnectionFactory(){
            RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration ();
            redisStandaloneConfiguration.setHostName(host);
            redisStandaloneConfiguration.setPort(port);
            redisStandaloneConfiguration.setPassword(password);
            JedisClientConfiguration.JedisClientConfigurationBuilder jedisClientConfiguration = JedisClientConfiguration.builder();
            JedisConnectionFactory factory = new JedisConnectionFactory(redisStandaloneConfiguration,
                    jedisClientConfiguration.build());
            return factory;
        }

        @Bean
        public RedisTemplate makeRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
            RedisTemplate redisTemplate = new RedisTemplate();
            redisTemplate.setConnectionFactory(redisConnectionFactory);
            return redisTemplate;
        }


}

//redis.properties

# Redis服务器地址
spring.data.redis.host=192.168.223.128
# Redis服务器连接端口
spring.data.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.data.redis.password=root

测试:

    @Test
    void two(){
        redisTemplate.opsForValue().set("two","hello");
        String two =(String) redisTemplate.opsForValue().get("two");
        System.out.println(two);
    }

在这里插入图片描述

Caused by: java.lang.NoClassDefFoundError: redis/clients/util/Pool

如果报错了,如标题的错误说明jedis版本高了,有冲突,降低jedis版本即可。

在这里插入图片描述

jedis从3.0.1版本降低到2.9.1版本。

Caused by: java.lang.NumberFormatException: For input string: “port”

Caused by: org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "port"
	at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:79) ~[spring-beans-5.3.24.jar:5.3.24]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1339) ~[spring-beans-5.3.24.jar:5.3.24]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1311) ~[spring-beans-5.3.24.jar:5.3.24]
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:657) ~[spring-beans-5.3.24.jar:5.3.24]
	... 88 common frames omitted
Caused by: java.lang.NumberFormatException: For input string: "port"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[na:1.8.0_181]
	at java.lang.Integer.parseInt(Integer.java:580) ~[na:1.8.0_181]
	at java.lang.Integer.valueOf(Integer.java:766) ~[na:1.8.0_181]
	at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:211) ~[spring-core-5.3.24.jar:5.3.24]
	at org.springframework.beans.propertyeditors.CustomNumberEditor.setAsText(CustomNumberEditor.java:115) ~[spring-beans-5.3.24.jar:5.3.24]
	at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:429) ~[spring-beans-5.3.24.jar:5.3.24]
	at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:402) ~[spring-beans-5.3.24.jar:5.3.24]
	at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:155) ~[spring-beans-5.3.24.jar:5.3.24]

在这里插入图片描述
连接redis时出现这个错误原因是:

Alt

port属性不能用int接收,改为Integer。

Caused by: java.lang.NumberFormatException: For input string: “port“

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
1.2为什么需要NoSQL 随着互联网web2.0网站的兴起,非关系型的数据库现在成了一个极其热门的新领域,非关系数据库产品的发展非常迅速。而传统的关系数据库在应付web2.0网站,特别是超大规模和高并发的SNS类型的web2.0纯动态网站已经显得力不从心,暴露了很多难以克服的问题,例如; 随着互联网Web2.0网站的兴起,非关系型的数据库现在成了一个极其热门的新领域,非关系数据库产品的发展非常迅速。而传统的关系数据库在应付Web2.0网站,特别是超大规模和高并发的SNS类型的Web2.0纯动态网站已经显得力不从心,暴露了很多难以克服的问题,例如; 1、High performance -对数据库高并发读写的需求 1、高性能-对数据库高并发读写的需求 web2.0网站要根据用户个性化信息来实时生成动态页面和提供动态信息,所以基本上无法使用动态页面静态化技术,因此数据库并发负载非常高,往往要达到每秒上万次读写请求。关系数据库应付上万次sQL查询还勉强顶得住,但是应付上万次SQL 写数据请求,硬盘lO就已经无法承受了。其实对于普通的BBS网站,往往也存在对高并发写请求的需求,例如网站的实时统计在线用户状态,记 Web2.0网站要根据用户个性化信息来实时生成动态页面和提供动态信息,所以基本上无法使用动态页面静态化技术,因此数据库并发负载非常高,往往要达到每秒上万次读写请求关系数据库应付上万次sql查询还勉强顶得住,但是应付上万次sql写数据请求,硬盘lo就已经无法承受了。其实对于普通的bbs网站,往往也存在对高并发写请求的需求,例如网站的实时统计在线用户状态,记
Spring Boot 可以很方便地与 Redis 进行集成。以下是一个简单的 Spring Boot 整合 Redis 的示例: 1. 添加 Redis 依赖 在 `pom.xml` 添加 Redis 相关依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置 Redis 连接信息 在 `application.properties` 文件中配置 Redis 的连接信息: ```properties spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= ``` 如果 Redis 没有设置密码,则 `spring.redis.password` 可以不用配置。 3. 编写 Redis 配置类 创建一个 Redis 配置类,用于配置 RedisTemplate 和 RedisConnectionFactory: ```java @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericToStringSerializer<>(Object.class)); return redisTemplate; } @Bean public RedisConnectionFactory redisConnectionFactory() { RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); redisStandaloneConfiguration.setHostName("localhost"); redisStandaloneConfiguration.setPort(6379); return new JedisConnectionFactory(redisStandaloneConfiguration); } } ``` 4. 使用 RedisTemplate 操作 Redis 在需要使用 Redis 的地方注入 RedisTemplate,然后就可以使用其提供的方法操作 Redis 了: ```java @RestController @RequestMapping("/redis") public class RedisController { @Autowired private RedisTemplate<String, Object> redisTemplate; @GetMapping("/set") public String set(String key, String value) { redisTemplate.opsForValue().set(key, value); return "success"; } @GetMapping("/get") public String get(String key) { Object value = redisTemplate.opsForValue().get(key); return value != null ? value.toString() : ""; } } ``` 以上示例中,我们使用了 RedisTemplate 的 `opsForValue` 方法来进行 Redis 的读写操作。 这样,我们就完成了 Spring Boot 整合 Redis 的操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xvwen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值