SpringBoot整合redis前置配置以及序列化
发布日期:2021-05-07 13:38:57 浏览次数:23 分类:精选文章

本文共 5811 字,大约阅读时间需要 19 分钟。

1.springboot引入redis的相关依赖,在pom.xml文件中加入:

org.springframework.boot
spring-boot-starter-data-redis

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
empRedisTemplate( RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate
template = new RedisTemplate
(); template.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer
ser = new Jackson2JsonRedisSerializer
(Employee.class); template.setDefaultSerializer(ser); return template; }

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

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

运行结果很成功,也很直观:

在这里插入图片描述

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

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

redis.clients
jedis

如果不做任何配置,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;@Componentpublic 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.注册拦截器
@Configurationpublic 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
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模板引擎取值显示:
230
/main.html
3490
/sql

显示效果:

在这里插入图片描述

上一篇:SpringBoot自定义缓存管理器
下一篇:linux上安装Redis

发表评论

最新留言

表示我来过!
[***.240.166.169]2025年03月31日 01时51分09秒