springboot引入redis并测试

1.添加依赖

        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-data-redis</artifactId>
       </dependency>
       <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>fastjson</artifactId>
           <version>1.2.3</version>
       </dependency>
       <dependency>
           <groupId>com.fasterxml.jackson.core</groupId>
           <artifactId>jackson-databind</artifactId>
       </dependency>

2.RedisConfig类

(暂时还不知道这个类的用处)

package com.config;


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
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.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;


@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * 选择redis作为默认缓存工具
     * @param redisConnectionFactory
     * @return
     */
    /*@Bean
    //springboot 1.xx
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        return rcm;
    }*/
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1)); // 设置缓存有效期一小时
        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration).build();
    }

    /**
     * retemplate相关配置
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();

        return template;
    }

    /**
     * 对hash类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }

    /**
     * 对redis字符串类型数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }

    /**
     * 对链表类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }

    /**
     * 对无序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }

    /**
     * 对有序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();
    }
}

3.在service中加入redis缓存

package com.service;

import com.dao.StudentMapper;

import com.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

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


@Service
public class UserService {

    @Resource
    private StudentMapper studentMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    public List<Student> queryAll() {
        return studentMapper.findAll();
    }

    /**
     * 获取用户策略:先从缓存中获取用户,没有则取数据表中 数据,再将数据写入缓存
     */
    public Student findUserById(String username) {
        String key = "user_" + username;

        ValueOperations<String, Student> operations = redisTemplate.opsForValue();

        //判断redis中是否有键为key的缓存
        boolean hasKey = redisTemplate.hasKey(key);

        if (hasKey) {
            Student s = operations.get(key);
            System.out.println("从缓存中获得数据:"+s.getSname());
            System.out.println("------------------------------------");
            return s;
        } else {
            Student s = studentMapper.findUserById(username);
            System.out.println("查询数据库获得数据:"+s.getSname());
            System.out.println("------------------------------------");

            // 写入缓存
            operations.set(key, s, 5, TimeUnit.HOURS);
            return s;
        }
    }
}

4.正常调用

package com.controller;

import com.dao.StudentMapper;
import com.entity.Student;
import com.service.StudentService;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

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

@Controller
public class helloController {

    @Resource
    private StudentService studentService;

    @Autowired
    private UserService RedisTestservice;

    @RequestMapping("/hello")
    public String hello() {
        return "/hello";
    }

    @RequestMapping("/login")
    public ModelAndView sumbit(String username,String password,String[] hobby,ModelMap modelmap) {
        for(String h :hobby) {
            System.out.println(h);
        }
        modelmap.addAttribute("username",username);

        /*List<Student> studentList =studentService.findAll();
        modelmap.addAttribute("studentList",studentList);*/
        System.out.println(username);
        Student s = RedisTestservice.findUserById(username);
        modelmap.addAttribute("s",s);
        return new ModelAndView("/index");

    }
}

5.结果:

6.Redis数据库

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于SpringBoot引入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或application.yml文件中配置Redis连接信息,例如: ```properties spring.redis.host=localhost spring.redis.port=6379 spring.redis.password=your_password spring.redis.database=0 ``` 3. 编写Redis配置类 创建Redis配置类,配置RedisTemplate和StringRedisTemplate等信息,例如: ```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 GenericJackson2JsonRedisSerializer()); return redisTemplate; } @Bean public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) { StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(); stringRedisTemplate.setConnectionFactory(redisConnectionFactory); stringRedisTemplate.setKeySerializer(new StringRedisSerializer()); stringRedisTemplate.setValueSerializer(new StringRedisSerializer()); return stringRedisTemplate; } } ``` 4. 编写Redis操作类 创建Redis操作类,通过@Autowired注入RedisTemplate或StringRedisTemplate,实现对Redis的操作,例如: ```java @Component public class RedisUtil { @Autowired private StringRedisTemplate stringRedisTemplate; public void set(String key, String value) { stringRedisTemplate.opsForValue().set(key, value); } public String get(String key) { return stringRedisTemplate.opsForValue().get(key); } public void delete(String key) { stringRedisTemplate.delete(key); } public void setExpire(String key, String value, long expireTime) { stringRedisTemplate.opsForValue().set(key, value, expireTime, TimeUnit.SECONDS); } } ``` 至此,SpringBoot引入Redis的步骤就完成了。 接下来,是关于接入的数据接口测试。可以通过Postman等工具进行测试,具体步骤如下: 1. 测试Redis写入操作 发送POST请求,请求地址为http://localhost:8080/redis/set,请求体为JSON格式的数据: ```json { "key": "name", "value": "Tom" } ``` 成功写入Redis后,返回结果为: ```json { "code": 200, "msg": "success" } ``` 2. 测试Redis读取操作 发送GET请求,请求地址为http://localhost:8080/redis/get,请求参数名为key,请求参数值为name,例如: ``` http://localhost:8080/redis/get?key=name ``` 成功读取Redis后,返回结果为: ```json { "code": 200, "msg": "success", "data": "Tom" } ``` 3. 测试Redis删除操作 发送DELETE请求,请求地址为http://localhost:8080/redis/delete,请求参数名为key,请求参数值为name,例如: ``` http://localhost:8080/redis/delete?key=name ``` 成功删除Redis后,返回结果为: ```json { "code": 200, "msg": "success" } ``` 4. 测试Redis设置过期时间操作 发送POST请求,请求地址为http://localhost:8080/redis/setExpire,请求体为JSON格式的数据: ```json { "key": "name", "value": "Tom", "expireTime": 60 } ``` 成功设置Redis过期时间后,返回结果为: ```json { "code": 200, "msg": "success" } ``` 以上就是关于SpringBoot引入Redis的步骤过程和接入的数据接口测试的详细介绍,希望能够对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值