spring 整合redis

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Tair(兼容Redis),内存型 2GB
简介: 用的是最新的jedis-2.6.2.jar这个包,这个和以前的有点不同。还需要添加spring-data-redis-1.2.1.RELEASE.jar和commons-pool2-2.3.jar。 在类路径下创建spring-redis-config.

用的是最新的jedis-2.6.2.jar这个包,这个和以前的有点不同。还需要添加spring-data-redis-1.2.1.RELEASE.jar和commons-pool2-2.3.jar。

在类路径下创建spring-redis-config.xml文件

复制代码
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"  
    xmlns:aop="http://www.springframework.org/schema/aop"  
    xsi:schemaLocation="  
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">  
            
     <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations" value="classpath:redis.properties"/>
    </bean>
     <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">  
        <property name="maxIdle" value="300" />  
        <property name="maxTotal" value="512" />  
        <property name="maxWaitMillis" value="1000" />  
        <property name="testOnBorrow" value="true" />  
    </bean>  
      
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  
        p:host-name="localhost" p:port="6379" p:password=""  p:pool-config-ref="poolConfig"/>  
      
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
        <property name="connectionFactory"   ref="connectionFactory" />  
    </bean>         

  

</beans>
复制代码

由于引用配置文件,使用不了表达式,这里写死了。使用表达式启动就报错,我也不知道为什么。

复制代码
##
redis.host=localhost  
##
redis.port=6379
##  
redis.pass=  
  
##
redis.maxIdle=300
##  
redis.maxTotal=512
##
redis.maxWaitMillis=1000 
##
redis.testOnBorrow=true
复制代码

redis.properties文件配置。

以前的版本应该有配置redis.maxActive但是看了源码,是没有setMaxActive方法的,所以不能注入,改用了redis.maxTotal。就因为这个弄了挺长时间的。

在web.xml配置spring-redis-config.xml文件

复制代码
<context-param>
     <param-name>contextConfigLocation</param-name>
    <param-value>
                <!-- 多个配置用,隔开 -->
        
                classpath*:spring-redis-config.xml
                
    </param-value>
</context-param>
复制代码

 

复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

public abstract class AbstractBaseRedisDao<V, K> {

    @Autowired
    protected RedisTemplate<K, V> redisTemplate;
    
    public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) {  
        this.redisTemplate = redisTemplate;  
    }  
      
    /** 
     * 获取 RedisSerializer 
     * <br>------------------------------<br> 
     */  
    protected RedisSerializer<String> getRedisSerializer() {  
        return redisTemplate.getStringSerializer();  
    }  
}
复制代码

创建一个抽象类,然后让使用到的类都继承这个方法。

复制代码
@Service("areaRedisService")
public class AreaRedisService<V, K> extends AbstractBaseRedisDao<V, K> {

    public boolean add(final Area area) {
        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = getRedisSerializer();
                byte[] key = serializer.serialize(area.getId()+"");
                byte[] name = serializer.serialize(area.getName());
                return connection.setNX(key, name);
            }
        });
        return result;
    }
    
     public Area get(final String keyId) {  
         Area result = redisTemplate.execute(new RedisCallback<Area>() {  
                public Area doInRedis(RedisConnection connection)  
                        throws DataAccessException {  
                    RedisSerializer<String> serializer = getRedisSerializer();  
                    byte[] key = serializer.serialize(keyId);  
                    byte[] value = connection.get(key);  
                    if (value == null) {  
                        return null;  
                    }  
                    String name = serializer.deserialize(value);  
                    return new Area(Integer.valueOf(keyId),name,null);  
                }  
            });  
            return result;  
        }  
}
复制代码

 

复制代码
    @Autowired
    AreaRedisService<?, ?> areaRedisService;

    private String path = "/WEB-INF/jsp/";
    
    @RequestMapping("/area/redis.htm")
    public ModelAndView areaRedis(HttpServletRequest request, HttpServletResponse response,String name) throws Exception {
        ModelAndView mv = new ModelAndView(path+"add.html");
        Area area = new Area();
        area.setCreateTime(new Date());
        area.setCommon(true);
        area.setDeleteStatus(false);
        area.setLevel(4);
        area.setName(name);
        area.setParentId(null);
        area.setSequence(1);
                area.setId(1);
        areaRedisService.add(area);
        mv.addObject("area", area);
    mv.addObject("arearedis",areaRedisService.get(area.getId()+""));
        return mv;
        
        
    }        
复制代码

这是controller的方法,这里使用了spring的注解。

使用注解,需要在上面的spring-redis-config.xml文件加入<context:component-scan base-package="基础包路径"/>配置了扫描路径可以不配置<context:annotation-config/>,因为前面的包含了后面的,他会激活@Controller,@Service,@Autowired,@Resource,@Component等注解。

http://www.cnblogs.com/hjy9420/p/4278002.html

 

相关文章
|
1月前
|
NoSQL Java 调度
分布式锁与分布式锁使用 Redis 和 Spring Boot 进行调度锁(不带 ShedLock)
分布式锁是分布式系统中用于同步多节点访问共享资源的机制,防止并发操作带来的冲突。本文介绍了基于Spring Boot和Redis实现分布式锁的技术方案,涵盖锁的获取与释放、Redis配置、服务调度及多实例运行等内容,通过Docker Compose搭建环境,验证了锁的有效性与互斥特性。
110 0
分布式锁与分布式锁使用 Redis 和 Spring Boot 进行调度锁(不带 ShedLock)
|
6月前
|
NoSQL 安全 Java
深入理解 RedisConnectionFactory:Spring Data Redis 的核心组件
在 Spring Data Redis 中,`RedisConnectionFactory` 是核心组件,负责创建和管理与 Redis 的连接。它支持单机、集群及哨兵等多种模式,为上层组件(如 `RedisTemplate`)提供连接抽象。Spring 提供了 Lettuce 和 Jedis 两种主要实现,其中 Lettuce 因其线程安全和高性能特性被广泛推荐。通过手动配置或 Spring Boot 自动化配置,开发者可轻松集成 Redis,提升应用性能与扩展性。本文深入解析其作用、实现方式及常见问题解决方法,助你高效使用 Redis。
612 4
|
7月前
|
NoSQL Java 关系型数据库
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 介绍
本文介绍在 Spring Boot 中集成 Redis 的方法。Redis 是一种支持多种数据结构的非关系型数据库(NoSQL),具备高并发、高性能和灵活扩展的特点,适用于缓存、实时数据分析等场景。其数据以键值对形式存储,支持字符串、哈希、列表、集合等类型。通过将 Redis 与 Mysql 集群结合使用,可实现数据同步,提升系统稳定性。例如,在网站架构中优先从 Redis 获取数据,故障时回退至 Mysql,确保服务不中断。
289 0
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 介绍
|
3月前
|
NoSQL Java Redis
Redis基本数据类型及Spring Data Redis应用
Redis 是开源高性能键值对数据库,支持 String、Hash、List、Set、Sorted Set 等数据结构,适用于缓存、消息队列、排行榜等场景。具备高性能、原子操作及丰富功能,是分布式系统核心组件。
429 2
|
5月前
|
消息中间件 缓存 NoSQL
基于Spring Data Redis与RabbitMQ实现字符串缓存和计数功能(数据同步)
总的来说,借助Spring Data Redis和RabbitMQ,我们可以轻松实现字符串缓存和计数的功能。而关键的部分不过是一些"厨房的套路",一旦你掌握了这些套路,那么你就像厨师一样可以准备出一道道饕餮美食了。通过这种方式促进数据处理效率无疑将大大提高我们的生产力。
206 32
|
7月前
|
NoSQL Java API
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Spring Boot 集成 Redis
本文介绍了在Spring Boot中集成Redis的方法,包括依赖导入、Redis配置及常用API的使用。通过导入`spring-boot-starter-data-redis`依赖和配置`application.yml`文件,可轻松实现Redis集成。文中详细讲解了StringRedisTemplate的使用,适用于字符串操作,并结合FastJSON将实体类转换为JSON存储。还展示了Redis的string、hash和list类型的操作示例。最后总结了Redis在缓存和高并发场景中的应用价值,并提供课程源代码下载链接。
1733 0
|
7月前
|
NoSQL Java Redis
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 安装
本教程介绍在 VMware 虚拟机(CentOS 7)或阿里云服务器中安装 Redis 的过程,包括安装 gcc 编译环境、下载 Redis(官网或 wget)、解压安装、修改配置文件(如 bind、daemonize、requirepass 等设置)、启动 Redis 服务及测试客户端连接。通过 set 和 get 命令验证安装是否成功。适用于初学者快速上手 Redis 部署。
168 0
|
NoSQL Java Redis
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
785 0
|
NoSQL Java Redis
SpringBoot集成Redis
SpringBoot集成Redis
562 0
|
NoSQL Java Redis
Springboot最全权限集成Redis-前后端分离-springsecurity-jwt-Token4
Springboot最全权限集成Redis-前后端分离-springsecurity-jwt-Token4
226 81