前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Redis整合Spring项目搭建实例

Redis整合Spring项目搭建实例

作者头像
CSDN技术头条
发布2018-02-09 17:51:23
9450
发布2018-02-09 17:51:23
举报
文章被收录于专栏:CSDN技术头条CSDN技术头条

本文介绍了如何使用注解的方式,将Redis缓存整合到你的Spring项目。

首先我们将使用jedis驱动,进而开始配置我们的Gradle。

代码语言:java
复制
group 'com.gkatzioura.spring'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.5.RELEASE")
    }
}
jar {
    baseName = 'gs-serving-web-content'
    version =  '0.1.0'
}
sourceCompatibility = 1.8
repositories {
    mavenCentral()
}
dependencies {
    compile "org.springframework.boot:spring-boot-starter-thymeleaf"
    compile 'org.slf4j:slf4j-api:1.6.6'
    compile 'ch.qos.logback:logback-classic:1.0.13'
    compile 'redis.clients:jedis:2.7.0'
    compile 'org.springframework.data:spring-data-redis:1.5.0.RELEASE'
    testCompile group: 'junit', name: 'junit', version: '4.11'
}
task wrapper(type: Wrapper) {
    gradleVersion = '2.3'
}

紧接着我们将使用Spring注解,继续执行Redis装载配置。

代码语言:java
复制
package com.gkatzioura.spring.config;
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.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public JedisConnectionFactory redisConnectionFactory() {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setUsePool(true);
        return jedisConnectionFactory;
    }
    @Bean
    public RedisSerializer redisStringSerializer() {
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        return stringRedisSerializer;
    }
    @Bean(name="redisTemplate")
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf,RedisSerializer redisSerializer) {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
        redisTemplate.setConnectionFactory(cf);
        redisTemplate.setDefaultSerializer(redisSerializer);
        return redisTemplate;
    }
    @Bean
    public CacheManager cacheManager() {
        return new RedisCacheManager(redisTemplate(redisConnectionFactory(),redisStringSerializer()));
    }
}

下一步将创建缓存接口CacheService。

代码语言:java
复制
package com.gkatzioura.spring.cache;
import java.util.Date;
import java.util.List;
public interface CacheService {
    public void addMessage(String user,String message);
    public List<String> listMessages(String user);
}

当然用户既可以增加一条消息也能取回一条消息。因此,在实现过程中,用户相关信息的存在时间将默认设为一分钟。

我们用Redis来继承实现CacheService接口。

代码语言:java
复制
package com.gkatzioura.spring.cache.impl;
import com.gkatzioura.spring.cache.CacheService;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
@Service("cacheService")
public class RedisService implements CacheService {
    @Resource(name = "redisTemplate")
    private ListOperations<String, String> messageList;
    @Resource(name = "redisTemplate")
    private RedisOperations<String,String> latestMessageExpiration;
    @Override
    public void addMessage(String user,String message) {
        messageList.leftPush(user,message);
        ZonedDateTime zonedDateTime = ZonedDateTime.now();
        Date date = Date.from(zonedDateTime.plus(1, ChronoUnit.MINUTES).toInstant());
        latestMessageExpiration.expireAt(user,date);
    }
    @Override
    public List<String> listMessages(String user) {
        return messageList.range(user,0,-1);
    }
}

我们的缓存机制将保留每个用户发送的消息列表。为了实现这个功能我们将调用ListOperations接口,同时将每个user作为一个key键值。通过RedisOperations接口,我们可以为key设置特定存在时长。在本例中,主要使用的是 user key。

下一步我们将创建一个controller注入缓存服务。

代码语言:java
复制
package com.gkatzioura.spring.controller;
import com.gkatzioura.spring.cache.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class MessageController {
    @Autowired
    private CacheService cacheService;
    @RequestMapping(value = "/message",method = RequestMethod.GET)
    @ResponseBody
    public List<String> greeting(String user) {
        List<String> messages = cacheService.listMessages(user);
        return messages;
    }
    @RequestMapping(value = "/message",method = RequestMethod.POST)
    @ResponseBody
    public String saveGreeting(String user,String message) {
        cacheService.addMessage(user,message);
        return "OK";
    }
}

最后完成类Application的创建。

代码语言:java
复制
package com.gkatzioura.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

经过如上步骤,接下来直接运行Application即可。

原文链接:Integrate Redis into a Spring Project( 译者/丘志鹏 审校/朱正贵 责编/仲浩)

译者简介:邱志鹏,关注大数据、机器学习。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2015-09-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 CSDN技术头条 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档