iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Springboot框架整合添加redis缓存功能
  • 616
分享到

Springboot框架整合添加redis缓存功能

2024-04-02 19:04:59 616人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录一:安装Redis二:添加Redis依赖三:添加Redis配置信息四:创建RedisConfigurer五:创建Redis常用方法六:接口测试Hello大家好,本章我们添加red

Hello大家好,本章我们添加redis缓存功能 。另求各路大神指点,感谢

一:安装Redis

因本人电脑是windows系统,从https://GitHub.com/ServiceStack/redis-windows下载了兼容windows系统的redis

下载后直接解压到自定义目录,运行cmd命令,进入到这个文件夹,在这个文件夹下运行下面命令,启动redis服务器

redis-server redis.windows.conf

运行下面命令进行测试:redis-cli

二:添加Redis依赖


<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-redis</artifactId>
   <version>1.4.5.RELEASE</version>
</dependency>

然后鼠标右键选择Maven→Reimport进行依赖下载

三:添加Redis配置信息

application.properties中添加

spring.redis.host=127.0.0.1

spring.redis.port=6379   

spring.redis.timeout=0

spring.redis.passWord=

四:创建RedisConfigurer


package com.example.demo.core.configurer;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.annotation.CachinGConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.JedisPoolConfig;


@Configuration
@EnableCaching   //开启缓存
public class RedisConfigurer extends CachingConfigurerSupport {

    @Bean
    @ConfigurationProperties(prefix="spring.redis")
    public JedisPoolConfig getRedisConfig(){
        JedisPoolConfig config = new JedisPoolConfig();
        return config;
    }

    @Bean
    @ConfigurationProperties(prefix="spring.redis")
    public JedisConnectionFactory getConnectionFactory(){
        JedisConnectionFactory factory = new JedisConnectionFactory();
        JedisPoolConfig config = getRedisConfig();
        factory.setPoolConfig(config);
        return factory;
    }


    @Bean
    public RedisTemplate<?, ?> getRedisTemplate(){
        RedisTemplate<?,?> template = new StringRedisTemplate(getConnectionFactory());
        return template;
    }
}

五:创建Redis常用方法

RedisService


package com.example.demo.service;

import java.util.List;


public interface RedisService {

    
    boolean set(String key, String value);

    
    String get(String key);

    
    boolean expire(String key, long expire);

    
    <T> boolean setList(String key, List<T> list);

    
    <T> List<T> getList(String key, Class<T> clz);

    
    long lpush(String key, Object obj);

    
    long rpush(String key, Object obj);

    
    String lpop(String key);

    
    long del(final String key);
}

RedisServiceImpl


package com.example.demo.service.impl;

import com.alibaba.fastJSON.jsON;
import com.example.demo.service.RedisService;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Service
public class RedisServiceImpl implements RedisService {

    @Resource
    private RedisTemplate<String, ?> redisTemplate;

    @Override
    public boolean set(final String key, final String value) {
        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                connection.set(serializer.serialize(key), serializer.serialize(value));
                return true;
            }
        });
        return result;
    }

    @Override
    public String get(final String key){
        String result = redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                byte[] value =  connection.get(serializer.serialize(key));
                return serializer.deserialize(value);
            }
        });
        return result;
    }

    @Override
    public long del(final String key){
        long result = redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                long value =  connection.del(serializer.serialize(key));
                return value;
            }
        });
        return result;
    }

    @Override
    public boolean expire(final String key, long expire) {
        return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }

    @Override
    public <T> boolean setList(String key, List<T> list) {
        String value = JSON.toJSONString(list);
        return set(key,value);
    }

    @Override
    public <T> List<T> getList(String key,Class<T> clz) {
        String json = get(key);
        if(json!=null){
            List<T> list = JSON.parseArray(json, clz);
            return list;
        }
        return null;
    }

    @Override
    public long lpush(final String key, Object obj) {
        final String value = JSON.toJSONString(obj);
        long result = redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                long count = connection.lPush(serializer.serialize(key), serializer.serialize(value));
                return count;
            }
        });
        return result;
    }

    @Override
    public long rpush(final String key, Object obj) {
        final String value = JSON.toJSONString(obj);
        long result = redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                long count = connection.rPush(serializer.serialize(key), serializer.serialize(value));
                return count;
            }
        });
        return result;
    }

    @Override
    public String lpop(final String key) {
        String result = redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                byte[] res =  connection.lPop(serializer.serialize(key));
                return serializer.deserialize(res);
            }
        });
        return result;
    }


}

六:接口测试

创建RedisController


package com.example.demo.controller;

import com.example.demo.core.ret.RetResponse;
import com.example.demo.core.ret.RetResult;
import com.example.demo.service.RedisService;
import org.springframework.WEB.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


@RestController
@RequestMapping("redis")
public class RedisController {

    @Resource
    private RedisService redisService;

    @PostMapping("/setRedis")
    public RetResult<String> setRedis(String name) {
        redisService.set("name",name);
        return RetResponse.makeOKRsp(name);
    }

    @PostMapping("/getRedis")
    public RetResult<String> getRedis() {
        String name = redisService.get("name");
        return RetResponse.makeOKRsp(name);
    }


}

输入Http://localhost:8080/redis/setRedis

输入http://localhost:8080/redis/getRedis

项目地址

码云地址:https://gitee.com/beany/mySpringBoot

GitHub地址:https://github.com/MyBeany/mySpringBoot

写文章不易,如对您有帮助,请帮忙点下star

结尾

添加redis缓存功能已完成,后续功能接下来陆续更新,另求各路大神指点,感谢大家。

到此这篇关于Springboot框架整合添加redis缓存功能的文章就介绍到这了,更多相关Springboot整合redis缓存内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Springboot框架整合添加redis缓存功能

本文链接: https://www.lsjlt.com/news/158418.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作