[置顶]SpringBoot实践 - SpringBoot+MySql+Redis

大家都知道redis的强大之处,在目前应用上也是大显神威。

先说说他的优点:

读写性能优异
支持数据持久化,支持AOF日志和RDB快照两种持久化方式
支持主从复制,主机会自动将数据同步到从机,可以进行读写分离。
数据结构丰富:除了支持string类型的value外还支持string、hash、set、sortedset、list等数据结构。

 

那么现在我们在 StringBoot+mysql的基础上引入Redis缓存中间件。

(关于SpringBoot+mysql的Demo可查看 SpringBoot+Mysql )

1.先看下完成后的代码结构

2. 操作如下
  a.在pom.xml引入如下依赖
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.0</version>
        </dependency>

 

  b.添加 RedisConfiguration.java

   

package com.example.config;

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;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

/** 
* @ClassName: RedisConfiguration 
* @Description: Redis Config
* @author mengfanzhu
* @date 2017年2月21日 下午2:03:26 
*/

@Configuration
public class RedisConfiguration {
    
    @Bean
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisFactory){
        StringRedisTemplate template = new StringRedisTemplate(redisFactory);
        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;
    }
}

 

  c.添加  UserRedis.java

  

package com.example.service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import com.example.entity.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/** 
* @ClassName: UserRedis 
* @Description:  redis 提供5种数据类型的操作
* String ,hash ,list , set , zset
* @author mengfanzhu
* @date 2017年2月21日 下午2:01:43 
*/
@Repository
public class UserRedis {
    
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    
    public void addUser(String key,Long time,User user){
        Gson gson = new Gson();
        redisTemplate.opsForValue().set(key, gson.toJson(user),time,TimeUnit.MINUTES);
    }
    
    public void addUserList(String key,Long time,List<User> userList){
        Gson gson = new Gson();
        redisTemplate.opsForValue().set(key, gson.toJson(userList),time,TimeUnit.MINUTES);
    }
    
    public User getUserByKey(String key){
        Gson gson = new Gson();
        User user = null;
        String userJson = redisTemplate.opsForValue().get(key);
        if(StringUtils.isNotEmpty(userJson)){
            user =  gson.fromJson(userJson, User.class);
        }
        return user;
    }
    
    public List<User> getUserListByKey(String key){
        Gson gson = new Gson();
        List<User> userList = null;
        String userJson = redisTemplate.opsForValue().get(key);
        if(StringUtils.isNotEmpty(userJson)){
            userList =  gson.fromJson(userJson, new TypeToken<List<User>>(){}.getType()    );
        }
        return userList;
    }
    
    public void deleteByKey(String key){
        redisTemplate.opsForValue().getOperations().delete(key);
    }
}

 

    d.添加 UserRedisService.java
package com.example.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.util.Assert;

import com.example.config.RedisConfiguration;
import com.example.entity.Department;
import com.example.entity.Role;
import com.example.entity.User;


/** 
* @ClassName: UserRedisService 
* @Description: user redis 
* @author mengfanzhu
* @date 2017年2月21日 下午2:25:39 
*/
@Service
@ContextConfiguration(classes = {RedisConfiguration.class,UserRedis.class} )
public class UserRedisService {
    
    private Logger logger = LoggerFactory.getLogger(UserRedisService.class);
    
    @Autowired
    private UserRedis userRedis;
    
    public void redisInitData(){
        Department department = new Department();
        department.setName("科技部REDIS");
        
        Role role = new Role();
        role.setName("管理员REDIS");
        List<Role> roleList = new ArrayList<Role>();
        roleList.add(role);
        
        User user =new User();
        user.setName("管理员REDIS");
        user.setLoginName("adminRedis");
        user.setCreatedate(new Date());
        user.setRoleList(roleList);
        user.setDepartment(department);
        logger.info("key:" + this.getClass().getName()+":userByLoginName:"+user.getLoginName());
        userRedis.deleteByKey(this.getClass().getName()+":userByLoginName:"+user.getLoginName());
        userRedis.addUser(this.getClass().getName()+":userByLoginName:"+user.getLoginName(),3600L,user);
        
    }
    
    public User getUserRedis(String loginName){
        User user = userRedis.getUserByKey(this.getClass().getName()+":userByLoginName:"+loginName);
        Assert.notNull(user,"用户为空!");
        logger.info("===user=== name:{},loginName: {},departmentName:{}, roleName:{}",
                user.getName(),user.getLoginName(),user.getDepartment().getName(),user.getRoleList().get(0).getName());
        return user;
    }
}

 

  e.application.yml 配置如下(redis host,port,password,database 注意)
  #redis
  redis:
    #database:9
    host: 100.100.100.100
    port: 1234
    password: 1234
    database: 1
    pool:
      max-idle: 8
      min-idle: 0
      max-active: 8 
      max-wait: -1
  f. UserController.java 添加

 

    @Autowired
    private UserRedisService userRedisService;
/** 
     * @Title: UserController
     * @Description: 初始化redis数据
     * @return  
     * @author mengfanzhu
     * @throws 
     */
    @RequestMapping("/initRedisdata")
    @ResponseBody
    public String initRedisData(){
        userRedisService.redisInitData();
        return "success";
    }
    @RequestMapping("/getUserRedisByLoginName/{loginName}")
    @ResponseBody
    public Map<String,Object> getUserRedisByLoginName(@PathVariable String loginName){
        Map<String,Object> result = new HashMap<String, Object>();
        User user = userRedisService.getUserRedis(loginName);
        Assert.notNull(user);
        result.put("name", user.getName());
        result.put("loginName", user.getLoginName());
        result.put("departmentName",user.getDepartment().getName());
        result.put("roleName", user.getRoleList().get(0).getName());
        return result;
    }
 3.运行效果
a.浏览器输入  localhost:9090/user/initRedisdata

b.查看redis

c.浏览器查看数据

代码已上传至 Github ,https://github.com/fzmeng/spring_boot_demo_hello
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值