spring 整合redis

本文涉及的产品
云数据库 Redis 版,标准版 2GB
推荐场景:
搭建游戏排行榜
云原生内存数据库 Tair,内存型 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

 

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
19天前
|
编解码 NoSQL Java
使用Spring Boot + Redis 队列实现视频文件上传及FFmpeg转码的技术分享
【8月更文挑战第30天】在当前的互联网应用中,视频内容的处理与分发已成为不可或缺的一部分。对于视频平台而言,高效、稳定地处理用户上传的视频文件,并对其进行转码以适应不同设备的播放需求,是提升用户体验的关键。本文将围绕使用Spring Boot结合Redis队列技术来实现视频文件上传及FFmpeg转码的过程,分享一系列技术干货。
57 3
|
24天前
|
缓存 NoSQL Java
【Azure Redis 缓存】示例使用 redisson-spring-boot-starter 连接/使用 Azure Redis 服务
【Azure Redis 缓存】示例使用 redisson-spring-boot-starter 连接/使用 Azure Redis 服务
|
30天前
|
NoSQL Java Redis
Redis6入门到实战------ 八、Redis与Spring Boot整合
这篇文章详细介绍了如何在Spring Boot项目中整合Redis,包括在`pom.xml`中添加依赖、配置`application.properties`文件、创建配置类以及编写测试类来验证Redis的连接和基本操作。
Redis6入门到实战------ 八、Redis与Spring Boot整合
|
17天前
|
NoSQL Redis 缓存
Redis 加持下的 Spring 应用性能革命:见证毫秒级响应速度,打造极致用户体验!
【8月更文挑战第31天】Redis 是一个高性能键值存储系统,常用于数据库、缓存及消息中间件。与 Spring 框架集成后,可显著提升应用性能,特别是在高并发场景下。本文通过电子商务网站商品详情页的例子,展示了如何配置 Redis 并使用 `RedisTemplate` 进行数据操作,通过缓存策略优化应用性能,减轻数据库压力。例如,在 `ProductService` 类中,先从 Redis 获取商品信息,若未命中则从数据库获取并缓存至 Redis。此外,还介绍了如何通过 REST 控制器模拟 HTTP 请求进行测试。在实际项目中,结合 Spring Cache 注解可更便捷地管理缓存策略。
30 0
|
20天前
|
缓存 NoSQL Java
惊!Spring Boot遇上Redis,竟开启了一场缓存实战的革命!
【8月更文挑战第29天】在互联网时代,数据的高速读写至关重要。Spring Boot凭借简洁高效的特点广受开发者喜爱,而Redis作为高性能内存数据库,在缓存和消息队列领域表现出色。本文通过电商平台商品推荐系统的实战案例,详细介绍如何在Spring Boot项目中整合Redis,提升系统响应速度和用户体验。
43 0
|
24天前
|
缓存 NoSQL Java
【Azure Redis 缓存】定位Java Spring Boot 使用 Jedis 或 Lettuce 无法连接到 Redis的网络连通性步骤
【Azure Redis 缓存】定位Java Spring Boot 使用 Jedis 或 Lettuce 无法连接到 Redis的网络连通性步骤
|
1月前
|
NoSQL 安全 Java
Java Spring Boot中使用Shiro、JWT和Redis实现用户登录鉴权
Java Spring Boot中使用Shiro、JWT和Redis实现用户登录鉴权
|
NoSQL Java 数据库
|
NoSQL Java Redis
redis和spring整合
pom构建: [html] view plain copy  print? &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;   &lt;groupId&gt;com.x.redis&lt;/groupId&gt;   &lt;artifactId&gt;springredis&l
1032 0
|
4天前
|
canal 缓存 NoSQL
Redis缓存与数据库如何保证一致性?同步删除+延时双删+异步监听+多重保障方案
根据对一致性的要求程度,提出多种解决方案:同步删除、同步删除+可靠消息、延时双删、异步监听+可靠消息、多重保障方案
Redis缓存与数据库如何保证一致性?同步删除+延时双删+异步监听+多重保障方案