SpringBoot整合redis前置配置以及序列化

本文的配置是基于这篇博客之上的
1.springboot引入redis的相关依赖,在pom.xml文件中加入:

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

2.配置redis的服务ip地址,在application.properties中指定:

#指定redis的主机地址
spring.redis.host=192.168.31.53

现在redis的环境已经搭建好了,测试一下,redis可否能用,在springboot的测试类写下面的测试代码:

 	@Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisTemplate redisTemplate;
    /**
     * Redis常见的五大数据类型
     *  String(字符串)、List(列表)、Set(集合)、Hash(散列)、ZSet(有序集合)
     *  stringRedisTemplate.opsForValue()[String(字符串)]
     *  stringRedisTemplate.opsForList()[List(列表)]
     *  stringRedisTemplate.opsForSet()[Set(集合)]
     *  stringRedisTemplate.opsForHash()[Hash(散列)]
     *  stringRedisTemplate.opsForZSet()[ZSet(有序集合)]
     */
    @Test
    public void test01(){
//        stringRedisTemplate.opsForValue().append("lp","88");
//        String a = stringRedisTemplate.opsForValue().get("lp");
//        System.out.println(a);

        stringRedisTemplate.opsForList().leftPush("mylist","1");
        stringRedisTemplate.opsForList().leftPush("mylist","2");
    }

发现操作一切正常!!!!!!
在这里插入图片描述
其实Reis环境配好了,那么使用方法跟缓存基础篇的玩法一样,只要你配好了环境,用的缓存就是redis。




序列化问题

想将对象放进redis中存储,就得解决下面的问题:

1.将对象所代表的类实现Serializable接口:

public class Employee implements Serializable {
	... ...
}

2.在测试类中模拟存储对象:

    @Autowired
    EmployeeMapper employeeMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisTemplate redisTemplate;
    
	@Test
    public void test02(){
        Employee employee = employeeMapper.getEmpById(1);
		redisTemplate.opsForValue().set("emp-01",employee);

    }

结果发现虽然存进入了,但key 和 value 我们都看不懂:
在这里插入图片描述
因为默认保存对象,使用的是jdk序列化机制,序列化后的数据保存到redis中。



springboot自然考虑到了这一点,所以我们可以自定义序列化的规则:将数据以json的方式保存,自己将对象转为json:
1.想完成这种转变,我们只需要将下面的bean加入容器:

    @Bean
    public RedisTemplate<Object, Employee> empRedisTemplate(
            RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate<Object, Employee> template = new RedisTemplate<Object, Employee>();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
        template.setDefaultSerializer(ser);
        return template;
    }

2.在操作时,不用原来的stringRedisTemplate和redisTemplate,而使用该bean来操作:

    @Autowired
    RedisTemplate<Object,Employee> empRedisTemplate;
    
    @Test
    public void test02(){
        Employee employee = employeeMapper.getEmpById(1);
        empRedisTemplate.opsForValue().set("emp-01",employee);
    }

运行结果很成功,也很直观:
在这里插入图片描述


使用Jedis来操作redis非关系型数据库

在上面的基础下,加下面的依赖:

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

如果不做任何配置,redis的连接工厂使用的依旧是lettuce
运行下面代码:

    @Autowired
    RedisConnectionFactory redisConnectionFactory;
    @Test
    void test1(){
        System.out.println(redisConnectionFactory.getClass());
    }

在这里插入图片描述
想要使用是jedis作为连接工厂,则还需在application.yml中配置:

spring:
  redis:
    host: 192.168.2.128
    port: 6379
    client-type: jedis  #!!!!!!!!!!!!!!!!!!!配置这个东西
    #下面的可以选择配置
#    jedis:
#      pool:
#        max-active: 10
    

再次运行上面的测试代码块结果如下:
在这里插入图片描述
下面写一个显示访问地址次数的demo:

1.编写拦截器:
package com.atguigu.admin.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class RedisUrlCountInterceptor implements HandlerInterceptor {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        //默认每次访问当前uri就会计数+1
        redisTemplate.opsForValue().increment(uri);
        return true;
    }
}

2.注册拦截器
@Configuration
public class AdminWebConfig implements WebMvcConfigurer{
    /**
     * Filter、Interceptor 几乎拥有相同的功能?
     * 1、Filter是Servlet定义的原生组件。好处,脱离Spring应用也能使用
     * 2、Interceptor是Spring定义的接口。可以使用Spring的自动装配等功能
     *
     */
    @Autowired
    RedisUrlCountInterceptor redisUrlCountInterceptor;
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
	     registry.addInterceptor(redisUrlCountInterceptor)
	                .addPathPatterns("/**")
	                .excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**",
	                        "/js/**","/aa/**");
    }


3.编写controller:
    @GetMapping("/main.html")
    public String mainPage(HttpSession session,Model model){
        ValueOperations<String, String> opsForValue =
                redisTemplate.opsForValue();
        String s = opsForValue.get("/main.html");
        String s1 = opsForValue.get("/sql");
        model.addAttribute("mainCount",s);
        model.addAttribute("sqlCount",s1);
        return "main";

    }
4.在main页面用themeleaf模板引擎取值显示:
                        <div class="col-md-6 col-xs-12 col-sm-6">
                            <div class="panel purple">
                                <div class="symbol">
                                    <i class="fa fa-gavel"></i>
                                </div>
                                <div class="state-value">
                                    <div class="value" th:text="${mainCount}">230</div>
                                    <div class="title">/main.html</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6 col-xs-12 col-sm-6">
                            <div class="panel red">
                                <div class="symbol">
                                    <i class="fa fa-tags"></i>
                                </div>
                                <div class="state-value">
                                    <div class="value" th:text="${sqlCount}">3490</div>
                                    <div class="title">/sql</div>
                                </div>
                            </div>
                        </div>

显示效果:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

键盘歌唱家

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

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

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

打赏作者

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

抵扣说明:

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

余额充值