`
wiselyman
  • 浏览: 2095314 次
  • 性别: Icon_minigender_1
  • 来自: 合肥
博客专栏
Group-logo
点睛Spring4.1
浏览量:82441
74ae1471-94c5-3ae2-b227-779326b57435
点睛Spring MVC4...
浏览量:130866
社区版块
存档分类
最新评论

Spring Boot使用redis做数据缓存

 
阅读更多


 1 添加redis支持

在pom.xml中添加

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
        </dependency>

 

2 redis配置

package com.wisely.ij.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
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.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.lang.reflect.Method;


@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{

    @Bean
    public KeyGenerator wiselyKeyGenerator(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };

    }

    @Bean
    public CacheManager cacheManager(
            @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
        return new RedisCacheManager(redisTemplate);
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(
            RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

 

 

3 redis服务器配置

# REDIS (RedisProperties)
spring.redis.database= # database name
spring.redis.host=localhost # server host
spring.redis.password= # server password
spring.redis.port=6379 # connection port
spring.redis.pool.max-idle=8 # pool settings ...
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.sentinel.master= # name of Redis server
spring.redis.sentinel.nodes= # comma-separated list of host:port pairs

 

4 应用

测试两个实体类

package com.wisely.ij.domain;


public class Address {
    private Long id;
    private String province;
    private String city;

    public Address(Long id,String province, String city) {
        this.id = id;
        this.province = province;
        this.city = city;
    }

    public Address() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}

 

package com.wisely.ij.domain;


public class User {
    private Long id;
    private String firstName;
    private String lastName;

    public User(Long id,String firstName, String lastName) {
        this.id = id ;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public User() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

 

 使用演示

package com.wisely.ij.service;

import com.wisely.ij.domain.Address;
import com.wisely.ij.domain.User;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * Created by wisely on 2015/5/25.
 */
@Service
public class DemoService {
    @Cacheable(value = "usercache",keyGenerator = "wiselyKeyGenerator")
    public User findUser(Long id,String firstName,String lastName){
        System.out.println("无缓存的时候调用这里");
        return new User(id,firstName,lastName);
    }
    @Cacheable(value = "addresscache",keyGenerator = "wiselyKeyGenerator")
    public Address findAddress(Long id,String province,String city){
        System.out.println("无缓存的时候调用这里");
        return new Address(id,province,city);
    }
}

 

package com.wisely.ij.web;

import com.wisely.ij.domain.Address;
import com.wisely.ij.domain.User;
import com.wisely.ij.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by wisely on 2015/5/25.
 */

@Controller
public class DemoController {

    @Autowired
    DemoService demoService;

    @RequestMapping("/test")
    @ResponseBody
    public String putCache(){
        demoService.findUser(1l,"wang","yunfei");
        demoService.findAddress(1l,"anhui","hefei");
        System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
        return "ok";
    }
    @RequestMapping("/test2")
    @ResponseBody
    public String testCache(){
        User user = demoService.findUser(1l,"wang","yunfei");
        Address address =demoService.findAddress(1l,"anhui","hefei");
        System.out.println("我这里没执行查询");
        System.out.println("user:"+"/"+user.getFirstName()+"/"+user.getLastName());
        System.out.println("address:"+"/"+address.getProvince()+"/"+address.getCity());
        return "ok";
    }
}

 

5 检验

 

先访问http://localhost:8080/test 保存缓存



 

再访问http://localhost:8080/test2 调用缓存里的数据

 



 

 

新书推荐《JavaEE开发的颠覆者: Spring Boot实战》,涵盖Spring 4.x、Spring MVC 4.x、Spring Boot企业开发实战。

 

京东地址:http://item.jd.com/11894632.html

当当地址:http://product.dangdang.com/23926195.html

亚马逊地址:http://www.amazon.cn/图书/dp/B01D5ZBFUK/ref=zg_bsnr_663834051_6 

淘宝地址:https://item.taobao.com/item.htm?id=528426235744&ns=1&abbucket=8#detail

 

 

 

或自己在京东、淘宝、亚马逊、当当、互动出版社搜索自选。

 




 

  • 大小: 269.4 KB
  • 大小: 56 KB
2
1
分享到:
评论
17 楼 jammyjaccy 2017-04-13  
你好,按照你书上的代码执行后有如下错误,作者能给解答一下吗!?

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.Objects out of START_ARRAY token
at [Source: [B@37551cbc; line: 1, column: 1]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:270) ~[jackson-databind-2.8.7.jar:2.8.7]
at com.fasterxml.jackson.databind.DeserializationContext.reportMappingException(DeserializationContext.java:1234) ~[jackson-databind-2.8.7.jar:2.8.7]
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1122) ~[jackson-databind-2.8.7.jar:2.8.7]
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1075) ~[jackson-databind-2.8.7.jar:2.8.7]
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromArray(BeanDeserializerBase.java:1378) ~[jackson-databind-2.8.7.jar:2.8.7]
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:174) ~[jackson-databind-2.8.7.jar:2.8.7]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:150) ~[jackson-databind-2.8.7.jar:2.8.7]
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3798) ~[jackson-databind-2.8.7.jar:2.8.7]
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2967) ~[jackson-databind-2.8.7.jar:2.8.7]
at org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer.deserialize(Jackson2JsonRedisSerializer.java:71) ~[spring-data-redis-1.7.8.RELEASE.jar:na]
at org.springframework.data.redis.core.AbstractOperations.deserializeValue(AbstractOperations.java:315) ~[spring-data-redis-1.7.8.RELEASE.jar:na]
at org.springframework.data.redis.core.AbstractOperations$ValueDeserializingRedisCallback.doInRedis(AbstractOperations.java:55) ~[spring-data-redis-1.7.8.RELEASE.jar:na]
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:204) ~[spring-data-redis-1.7.8.RELEASE.jar:na]
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:166) ~[spring-data-redis-1.7.8.RELEASE.jar:na]
at org.springframework.data.redis.core.AbstractOperations.execute(AbstractOperations.java:88) ~[spring-data-redis-1.7.8.RELEASE.jar:na]
at org.springframework.data.redis.core.DefaultValueOperations.get(DefaultValueOperations.java:43) ~[spring-data-redis-1.7.8.RELEASE.jar:na]
at com.example.dao.PersonDao.getPerson(PersonDao.java:43) ~[classes/:na]
at com.example.dao.PersonDao$$FastClassBySpringCGLIB$$3ce6a50.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:721) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at com.example.dao.PersonDao$$EnhancerBySpringCGLIB$$6c39a2a2.getPerson(<generated>) ~[classes/:na]
at com.example.controller.DataController.getPerson(DataController.java:85) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_111]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_111]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_111]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_111]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.11.jar:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474) [tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) [tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783) [tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798) [tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434) [tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.11.jar:8.5.11]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_111]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_111]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.11.jar:8.5.11]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_111]

16 楼 lixiaoxiong5 2016-10-05  
@作者 汪云飞
你好,请问,如果要设置某个键的过期时间 ,应当如何操作???
15 楼 lixiaoxiong5 2016-10-05  
你好,请问,如果要设置某个键的过期时间 ,应当如何操作???
14 楼 paker1989 2016-07-06  
我配置完以后报这个错:
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
Caused by: java.lang.IllegalArgumentException: Incorrect number of transaction results. Expected: 4 Actual: 0
at org.springframework.data.redis.connection.convert.TransactionResultConverter.convert(TransactionResultConverter.java:52)
at org.springframework.data.redis.connection.jedis.JedisConnection.exec(JedisConnection.java:760)
... 57 more
13 楼 jKingLing 2016-05-30  
请问 @Cacheable(value = "usercache",里面的usercache是从哪来的
12 楼 www314599782 2016-04-21  
不行啊 Jackson2JsonRedisSerializer
java.util.LinkedHashMap cannot be cast to com.dandanlicai.model.StockNews
还是用jdk的吧
11 楼 13270735231 2015-10-20  
你好,问一下这种方式的话缓存失效在哪里配置哇
10 楼 pyzheng 2015-09-24  
你倒数第二张图片, RedisClient是什么软件呀?  我一直想找这玩意
9 楼 idda 2015-08-21  
您好,请问您依赖的jackson是哪个版本的?
我从2.5试到2.6,都报错。
java.lang.NoSuchMethodError: com.fasterxml.jackson.core.JsonParser.setCurrentValue(Ljava/lang/Object;)V
8 楼 徐茂才 2015-05-25  
wiselyman 写道
徐茂才 写道
wiselyman 写道
徐茂才 写道
“template.setValueSerializer(new Jackson2JsonRedisSerializer<SysUser>( 
                SysUser.class)); //请注意这里  ”这里能配置统一的实体吗?


你等下,我更新下这个例子

方便给您的demo源码给我看下吗?我怎么试都出错,我QQ号:330183954


源码都贴上去了,这个好测试,数据库都不需要

非常感谢, ,如果设置Object类型需要设置对象映射(ObjectMapper)
7 楼 wiselyman 2015-05-25  
徐茂才 写道
wiselyman 写道
徐茂才 写道
“template.setValueSerializer(new Jackson2JsonRedisSerializer<SysUser>( 
                SysUser.class)); //请注意这里  ”这里能配置统一的实体吗?


你等下,我更新下这个例子

方便给您的demo源码给我看下吗?我怎么试都出错,我QQ号:330183954


源码都贴上去了,这个好测试,数据库都不需要
6 楼 徐茂才 2015-05-25  
wiselyman 写道
徐茂才 写道
“template.setValueSerializer(new Jackson2JsonRedisSerializer<SysUser>( 
                SysUser.class)); //请注意这里  ”这里能配置统一的实体吗?


你等下,我更新下这个例子

方便给您的demo源码给我看下吗?我怎么试都出错,我QQ号:330183954
5 楼 wiselyman 2015-05-25  
徐茂才 写道
“template.setValueSerializer(new Jackson2JsonRedisSerializer<SysUser>( 
                SysUser.class)); //请注意这里  ”这里能配置统一的实体吗?


你等下,我更新下这个例子
4 楼 wiselyman 2015-05-25  
徐茂才 写道
“template.setValueSerializer(new Jackson2JsonRedisSerializer<SysUser>( 
                SysUser.class)); //请注意这里  ”这里能配置统一的实体吗?


我测试了一下,保持原有代码不动也是支持不同的实体序列化的,
改为
template.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class));  

也是可以的
3 楼 徐茂才 2015-05-25  
wiselyman 写道
徐茂才 写道
“template.setValueSerializer(new Jackson2JsonRedisSerializer<SysUser>( 
                SysUser.class)); //请注意这里  ”这里能配置统一的实体吗?


应该这样写吧:
template.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class));

你测试一下,应该可以,记得告诉我结果


不可以,报转换异常:java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to...
2 楼 wiselyman 2015-05-25  
徐茂才 写道
“template.setValueSerializer(new Jackson2JsonRedisSerializer<SysUser>( 
                SysUser.class)); //请注意这里  ”这里能配置统一的实体吗?


应该这样写吧:
template.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class));

你测试一下,应该可以,记得告诉我结果

1 楼 徐茂才 2015-05-25  
“template.setValueSerializer(new Jackson2JsonRedisSerializer<SysUser>( 
                SysUser.class)); //请注意这里  ”这里能配置统一的实体吗?

相关推荐

    Spring Boot整合Redis做集中式缓存

    在一些要求高一致性(任何数据变化都能及时的被查询到)的系统和应用中,就不能再使用EhCache来解决了,这个时候使用集中式缓存是个不错的选择,因此本文将介绍如何在Spring Boot的缓存支持中使用Redis进行数据缓存...

    详解Spring Boot使用redis实现数据缓存

    在本文中,我们将深入探讨如何在Spring Boot应用中利用Redis作为数据缓存系统。Spring Boot以其简化微服务开发的特性,结合Redis的高效缓存能力,可以为应用程序提供高效的性能优化。 首先,集成Spring Boot与Redis...

    35.[视频] Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】

    - **启用Redis缓存**:通过在配置类中启用`@EnableCaching`注解,Spring Boot将自动扫描并处理缓存注解。 2. **Redis缓存注解** - **@Cacheable**:此注解用在方法上,表示该方法的结果会被缓存。可以通过指定`...

    Spring Boot整合redis

    以上就是Spring Boot整合Redis的相关知识点,包括配置、数据操作、模板引擎Thymeleaf、数据源Druid、声明式事务管理和Redis事务的使用。通过这些知识,你可以构建一个具备数据缓存能力的Web应用。

    spring boot+redis单机与集群.zip

    总结来说,这个压缩包文件的内容将涵盖Spring Boot项目中集成Redis的基本步骤,包括设置单机和集群模式,以及如何在应用中使用Redis进行数据缓存。对于初学者,这将是一个很好的实践指南,而对于有经验的开发者,也...

    Spring Boot整合Redis的完整步骤

    本文将详细介绍Spring Boot整合Redis的完整步骤,包括Spring Boot对Redis的支持、添加依赖、配置RedisTemplate和StringRedisTemplate、使用Redis缓存等。 一、Spring Boot对Redis的支持 Spring Boot对Redis的支持...

    3.1、spring boot redis注解缓存Cacheable (value) 1

    在spring boot 项目中,使用redis缓存机制需要引入相关依赖关系。首先,在pom.xml文件中引入spring boot 父节点依赖关系: ```xml &lt;groupId&gt;org.springframework.boot &lt;artifactId&gt;spring-boot-starter-parent ...

    Spring boot 和 Redis集成例子.zip

    在现代的Web应用开发中,Spring Boot和Redis的结合使用非常常见,因为它们能提供高效、灵活的数据存储和快速响应。Spring Boot简化了基于Spring的应用程序的开发过程,而Redis则是一个高性能的键值数据库,适合处理...

    spring boot集成redis做为通用缓存的实战demo,帮助大家彻底掌握s-cache-practice.zip

    在本实战项目 "s-cache-practice" 中,我们将学习如何将 Redis 集成到 Spring Boot 应用中,以实现通用缓存功能。 首先,让我们了解集成的步骤: 1. **添加依赖**:在 `pom.xml` 文件中,我们需要引入 Spring Boot...

    (源码)基于Spring Boot和Redis的秒杀系统.zip

    本项目是一个基于Spring Boot框架和Redis缓存的秒杀系统。系统主要功能包括用户登录、商品展示、秒杀活动处理等。通过使用Redis和RabbitMQ,系统能够高效处理高并发的秒杀请求,确保系统的稳定性和性能。 ## 项目的...

    Spring boot 集成 redis (解决String类型乱码) 缓存用redis

    最后,启动Spring Boot应用,现在你的系统已经集成了Redis缓存,并解决了String类型的乱码问题。在实际应用中,还可以根据需求调整缓存策略,比如设置过期时间、缓存更新策略等。 总的来说,Spring Boot与Redis的集...

    spring boot - redis-1

    如果你使用的是Spring Boot 2.0及以上版本,还可以利用`ReactiveRedisTemplate`进行响应式编程,以实现非阻塞的数据操作。 6. **使用Redisson客户端** 除了Spring Data Redis提供的模板,还可以选择使用Redisson...

    Spring Boot中使用Redis做缓存的方法实例

    Spring Boot 中使用 Redis 做缓存的方法实例 在本文中,我们将详细介绍如何在 Spring Boot 中使用 Redis 做缓存。缓存是一种非常重要的技术,可以极大地提高应用程序的性能。Redis 是一个非常流行的 Nosql 数据库,...

    spring boot 集成redis代码

    在本文中,我们将深入探讨如何在Spring Boot应用中集成Redis,以便利用其高效的数据存储和检索功能。Redis是一个开源的、内存数据结构存储系统,它可以用作数据库、缓存和消息代理。Spring Boot是Spring框架的一个轻...

    Spring boot基于redis实现附近的人

    本项目是关于如何利用Spring Boot结合Redis这一高效内存数据存储系统来实现“附近的人”功能。这个功能通常应用于社交应用,让用户能够发现并连接到地理位置相近的其他用户。 首先,让我们深入了解Spring Boot。...

    Spring Boot 使用 Redis.docx

    }}在 Spring Boot 中,Redis 可以作为缓存系统和数据库的辅助工具。这里我们关注两个典型的应用场景: 1. **作为缓存**:Spring Boot 的 `@EnableCaching` 注解可以开启缓存支持,通过 `@Cacheable`、`@CacheEvict...

    Spring boot -redis

    6. 使用 Redis:在业务代码中,可以使用 Spring Data Redis 提供的方法存取数据,同时享受到过期事件的监听功能。 通过以上步骤,我们可以实现 Spring Boot 应用中对 Redis 的高效集成,并能够监听并处理 Redis 的...

    spring boot整合redis demo代码

    本示例将详细介绍如何在Spring Boot项目中整合Redis,实现数据的高效存储与访问。 一、集成Redis 1. 添加依赖 在Spring Boot项目的`pom.xml`文件中,我们需要引入Spring Data Redis和Spring Boot的Redis starter...

    (源码)基于Spring Boot和Redis的积分管理系统.zip

    使用Redis进行数据缓存,提高系统性能。 分布式锁机制,确保并发操作的数据一致性。 3. API接口 提供RESTful API接口,支持用户积分的更新、查询等操作。 支持gRPC协议,提供高性能的远程调用服务。 4. 后台...

    (源码)基于Spring Boot和Redis的铁路在线购票系统.zip

    2. Redis缓存使用Redis作为旁路缓存,实现与数据库的最终一致性,并通过Redis + Lua脚本防止车票超卖。 3. JWT用户验证使用JWT(JSON Web Token)进行用户登录验证,确保用户身份的合法性。 4. RocketMQ流量削峰通过...

Global site tag (gtag.js) - Google Analytics