Redis整合Spring專案搭建例項
阿新 • • 發佈:2022-04-28
本文介紹瞭如何使用註解的方式,將Redis快取整合到你的Spring專案。
首先我們將使用jedis驅動,進而開始配置我們的Gradle。
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裝載配置。
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。
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介面。
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注入快取服務。
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的建立。
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( 譯者/丘志鵬 審校/朱正貴 責編/仲浩)
譯者簡介:邱志鵬,關注大資料、機器學習。