Spring Boot(三)

来源:互联网 发布:纳粹军装淘宝 编辑:程序博客网 时间:2024/06/08 17:59

今天带来的是SpringBoot使用Redis缓存,先从简单的开始。

首先配置依赖:

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

然后创建用户实体的Redis服务类:

package com.example.demo.redis;import com.example.demo.bean.User;import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Repository;import org.springframework.util.StringUtils;import java.util.List;import java.util.concurrent.TimeUnit;@Repositorypublic class UserRedis {    @Autowired    private RedisTemplate<String, String> redisTemplate;    public void add(String key, Long time, User user){        Gson gson = new Gson();        redisTemplate.opsForValue().set(key, gson.toJson(user), time, TimeUnit.MINUTES);    }    public void add(String key, Long time, List<User> users){        Gson gson = new Gson();        redisTemplate.opsForValue().set(key, gson.toJson(users), time, TimeUnit.MINUTES);    }    public User get(String key){        Gson gson = new Gson();        User user = null;        String userJson = redisTemplate.opsForValue().get(key);        if(!StringUtils.isEmpty(userJson)){            user = gson.fromJson(userJson, User.class);        }        return user;    }    public List<User> getList(String key){        Gson gson = new Gson();        List<User> lists = null;        String listJson = redisTemplate.opsForValue().get(key);        if (!StringUtils.isEmpty(listJson)){            lists = gson.fromJson(listJson, new TypeToken<List<User>>(){}.getType());        }        return lists;    }    public void delete(String key){        redisTemplate.opsForValue().getOperations().delete(key);    }}

这里使用Gson将对象转成JSON

<dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.2.4</version></dependency>

在我自己的开发中使用的是下面的方式转化:

import com.alibaba.fastjson.JSON;
JSON.toJSONString(Object)


接下来在我们的配置类中初始化RedisTemplate,主要是对它存取的字符串进行JSON格式的初始配置。

package com.example.demo.configuration;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;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;@Configurationpublic class RedisConfig {    @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;    }}

安装Redis服务器:

Redis下载地址

安装好之后点击redis-server.exe 即可启动服务。


启动之后的界,默认端口是6379:


配置Redis:

#redis配置spring.redis.host=127.0.0.1spring.redis.port=6379spring.redis.pool.max-idle=8spring.redis.pool.min-idle=0spring.redis.pool.max-active=8spring.redis.pool.max-wait=-1

好了,写我们的测试方法吧:

package com.example.demo;import com.example.demo.bean.Deparment;import com.example.demo.bean.Role;import com.example.demo.bean.User;import com.example.demo.redis.UserRedis;import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWith;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import org.springframework.util.Assert;import java.util.ArrayList;import java.util.Date;import java.util.List;@SpringBootTest@RunWith(SpringJUnit4ClassRunner.class)//@ContextConfiguration(classes = {RedisConfig.class, UserRedis.class})public class RedisTest {    private Logger logger = LoggerFactory.getLogger(RedisTest.class);    @Autowired    UserRedis userRedis;    @Before    public void setup(){        Department department = new Department();        department.setName("开发部");        Role role = new Role();        role.setName("admin");        User user = new User();        user.setName("user");        user.setCreatedate(new Date());        user.setDepartment(department);        List<Role> roles = new ArrayList<>();        roles.add(role);        user.setRoles(roles);        userRedis.delete(this.getClass().getName() + ": userByname:" + user.getName());        userRedis.add(this.getClass().getName() + ": userByname:" + user.getName(), 10L, user);    }    @Test    public void get(){        User user = userRedis.get(this.getClass().getName() + ": userByname:user");        Assert.notNull(user);        logger.info("====user==== name:{}, department:{}, role:{}", user.getName(), user.getDepartment().getName(), user.getRoles().get(0).getName());    }}

结果:



好了,下次整理一下使用druid和Redis提高数据库访问性能

原创粉丝点击