Java随笔 | Springboot项目中引入并使用redis(步骤)


在Springboot项目中使用Redis需先确保服务器(或主机)已安装Redis并开启端口。
在业务层中使用Redis有两种装配方式,两者任选其一即可。

  • RedisTemplate装配:需要先创建配置类,指定序列化策略,再在业务层中使用,获取数据时接收类型为实体类集合。
  • StringRedisTemplate装配:默认所有数据都是字符串形式,在取得数据后再解析为相应实体类集合。

第一步:导入依赖

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

第二步:配置application.yml

# 配置数据库连接参数
spring:
  redis:  # redis数据库配置
    host: 192.168.xxx.xxx  # ip
    port: 6379  # 默认端口

第三步:在业务层中使用Redis(两种方式任选一即可)

方式1:RedisTemplate装配

先 · 创建配置类RedisConfig

注意:对应的实体类需要可序列化

@Configuration// 该注解表示该类为springboot的配置类,会被自动解析,本类为固定写法
public class RedisConfig {

    @Bean// 将该方法的返回值加入到容器
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        // 1.创建一个redis模板对象
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);// 设置连接器

        // 2.配置redis模板的普通键值对的序列化策略
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));

        // 3.配置redis模板的Hash键值对的序列化策略
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());

        // 4.返回该redis模板对象,加入到spring容器中
        return redisTemplate;
    }
}

再 · RedisTemplate父类装配

@Service
public class RedisServiceImpl extends ServiceImpl<RedisDao, BookType> implements RedisService {

    // 引入redis模板类,该类是一个父类,其可用于设置序列化策略、获取操作redis的接口对象、设置key的有效时间等
    @Resource// 需使用@Resource注解装填
    private RedisTemplate<String, BookType> redisTemplate;

    @Override// 注意使用RedisTemplate对象需要写redis配置类 配置序列化策略
    public List<BookType> getTypes() {
        // 1.通过redisTemplate获取操作redis的接口对象
        ListOperations<String, BookType> listOperations = redisTemplate.opsForList();

        // 2.通过接口对象listOperations获取redis中的数据 key为book_type 直接用List<BookType>接收
        List<BookType> types = listOperations.range("book_type", 0, -1);

        // 3.如果不为null 表示存在数据 直接return即可
        if(!ObjectUtils.isEmpty(types)) return types;

        // 4.如果为null 表示redis中不存在该数据 需要查询mysql并将其保存到redis中
        List<BookType> bookTypes = this.list();
        listOperations.leftPushAll("book_type", bookTypes);
        // redisTemplate.expire("book_type", 20L, TimeUnit.SECONDS);// 设置20秒过期
        return bookTypes;
    }
}

方式2:StringRedisTemplate装配

@Service
public class StringRedisServiceImpl extends ServiceImpl<RedisDao, BookType> implements StringRedisService {
    @Autowired// 引入StringRedis模板 StringRedisTemplate是RedisTemplate的子类 故不带泛型 可使用@Autowired装配
    private StringRedisTemplate redisTemplate;

    @Autowired// 该对象来自spring-boot-starter-web依赖 用于字符串转和List集合互转
    private ObjectMapper objectMapper;

    @Override// 使用StringRedisTemplate不需要进行序列化配置
    public List<BookType> getTypes() throws JsonProcessingException {
        // 1.通过redisTemplate获取操作redis的接口对象 该对象只操作字符串
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();

        // 2.通过接口对象valueOperations获取redis中的数据 key为book_type 接受类型为String
        String types = valueOperations.get("book_type");

        // 3.如果不是空字符串 表示存在数据 转换为List后返回 转换时指定泛型为实体类
        if (StringUtils.hasLength(types))
        	return objectMapper.readValue(types, new TypeReference<List<BookType>>() {});

        // 4.如果是空字符串 表示redis中不存在该数据 需要查询mysql并将其保存到redis中
        List<BookType> bookTypes = this.list();
        String typesStr = objectMapper.writeValueAsString(bookTypes);// 列表转字符串
        valueOperations.set("book_type", typesStr);
        // valueOperations.set("book_type", typesStr, 20L, TimeUnit.SECONDS);// 存值并设置20秒过期
        return bookTypes;
    }
}

附:本文示例中的实体类

// 实体类 图书类型 可序列化
public class BookType implements Serializable {
    private static final long serialVersionUID = 1L;
    private Integer typeId;
    private String typeName;
    private Integer parentId;
    private Integer typeState;
    private Integer typeSelf;
}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 可以使用Jedis工具类来扫描其他Spring Boot项目使用Redis地址。首先,需要在pom.xml文件添加Jedis依赖,然后在Java代码使用Jedis的API来连接Redis服务器并扫描Redis地址。具体实现可以参考以下代码: ```java import redis.clients.jedis.Jedis; import redis.clients.jedis.ScanParams; import redis.clients.jedis.ScanResult; public class RedisScanner { public static void main(String[] args) { // 连接Redis服务器 Jedis jedis = new Jedis("localhost", 6379); // 扫描Redis地址 ScanParams params = new ScanParams().match("*"); String cursor = ""; do { ScanResult<String> result = jedis.scan(cursor, params); for (String key : result.getResult()) { System.out.println(key); } cursor = result.getStringCursor(); } while (!cursor.equals("")); // 关闭连接 jedis.close(); } } ``` ### 回答2: 要使用Java代码静态扫描其他Spring Boot项目使用Redis地址,可以采取以下步骤: 1. 引入必要的依赖: 在项目的pom.xml文件添加Spring Boot和Redis相关的依赖,例如: ```xml <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- Redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 创建一个Java类来执行扫描操作: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.redis.RedisProperties; import org.springframework.context.ApplicationContext; @SpringBootApplication public class RedisScanner { public static void main(String[] args) { ApplicationContext context = SpringApplication.run(RedisScanner.class, args); RedisProperties redisProperties = context.getBean(RedisProperties.class); System.out.println("Redis地址:" + redisProperties.getHost() + ":" + redisProperties.getPort()); } } ``` 3. 运行扫描程序: 在命令行或IDE执行扫描程序的main方法,它将启动一个Spring Boot应用程序并输出Redis地址。 注意:确保已经正确配置了被扫描项目Redis连接信息,扫描程序需要能够获取到该信息才能输出正确的Redis地址。 通过以上步骤,你可以使用Java代码静态扫描其他Spring Boot项目使用Redis地址,并将其输出到控制台或其他你需要的地方。 ### 回答3: 要使用Java代码静态扫描其他Spring Boot项目使用Redis地址,可以使用以下步骤: 1. 导入相关的Java类库和依赖:首先需要导入Spring Boot的相关类库,如spring-boot-starter-data-redis,以及RedisJava客户端类库,如jedis或Lettuce。 2. 获取其他项目的源代码:将其他Spring Boot项目的源代码进行获取,可以通过Git克隆或下载压缩包的方式获取。 3. 遍历源代码文件:通过递归方式遍历其他项目的源代码文件夹,可以使用Java的File类和FileUtils类。 4. 搜索Redis连接配置:在遍历的过程,对每个文件进行解析,搜索Redis连接配置的相关代码。可以通过正则表达式匹配关键字,如"RedisTemplate"、"Redisson"等。 5. 提取Redis地址:根据找到的连接配置代码,提取其Redis地址信息。可以通过字符串截取、正则表达式或代码解析等方式提取Redis连接地址。 6. 封装结果:将提取到的Redis地址保存到一个列表或其他数据结构,用于后续的使用或输出。 7. 输出结果:根据需求来定义如何输出结果,可以将结果保存到日志文件、数据库或控制台显示出来。 需要注意的是,以上步骤仅是一个大致的思路,具体的实现方式可能因项目的结构和要求而有所不同。在实现过程,还需要考虑文件过滤、异常处理、性能调优等因素。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序猿林仔

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

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

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

打赏作者

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

抵扣说明:

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

余额充值