SpringBoot入门系列:第四篇 redis

  • Post author:
  • Post category:其他


一,准备工作,建立spring-boot-sample-redis工程

1、http://start.spring.io/

A、Artifact中输入spring-boot-sample-redis

B、勾选Web下的web

C、勾选NOSQL下的Redis

2、Eclips中导入工程spring-boot-sample-redis

A、解压快捷工程spring-boot-sample-redis到某文件夹

B、eclips中file->import->Import Existing Maven Projects–>Select Maven projects–>finish导入工程

3、工程导入之后,文件结构如下图

4、在包com.example下建立web文件夹

5、便于测试,引入spring-boot-sample-helloworld的HelloController及配置文件logback.xml

HelloController代码为

package com.example.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

	protected static Logger logger=LoggerFactory.getLogger(HelloController.class);
	
	@RequestMapping("/")
	public String helloworld(){
		logger.debug("访问hello");
		return "Hello world!";
	}
	
	@RequestMapping("/hello/{name}")
	public String helloName(@PathVariable String name){
		logger.debug("访问helloName,Name={}",name);
		return "Hello "+name;
	}
}

logback.xml配置为

<configuration>  
    <!-- %m输出的信息,%p日志级别,%t线程名,%d日期,%c类的全名,,,, -->  
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">  
        <encoder>  
            <pattern>%d %p (%file:%line\)- %m%n</pattern>
            <charset>GBK</charset> 
        </encoder>  
    </appender>  
    <appender name="baselog"  
        class="ch.qos.logback.core.rolling.RollingFileAppender">  
        <File>log/base.log</File>  
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
            <fileNamePattern>log/base.log.%d.i%</fileNamePattern>  
            <timeBasedFileNamingAndTriggeringPolicy  class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">  
        		<!-- or whenever the file size reaches 64 MB -->  
        		<maxFileSize>64 MB</maxFileSize>  
      		</timeBasedFileNamingAndTriggeringPolicy>  
        </rollingPolicy>  
        <encoder>  
            <pattern>  
                %d %p (%file:%line\)- %m%n
            </pattern>  
            <charset>UTF-8</charset> <!-- 此处设置字符集 --> 
        </encoder>  
    </appender>  
    <root level="info">  
        <appender-ref ref="STDOUT" />  
    </root>  
    <logger name="com.example" level="DEBUG">  
        <appender-ref ref="baselog" />  
    </logger>  
</configuration>

注:logback.xml文件位于src/main/resources下

6、启动工程,通过浏览器查看正确性

http://localhost:8080/

http://localhost:8080/hello/上帝

二,使用StringRedisTemplate

1、web文件下建立class,类名为StringRedisController,编写StringRedisController为

package com.example.web;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StringRedisController {
    
    protected static Logger logger=LoggerFactory.getLogger(StringRedisController.class);
    
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    
    @Resource(name="stringRedisTemplate")
    ValueOperations<String,String> valOpsStr;
    
    @RequestMapping("set")
    public String setKeyAndValue(String key,String value){
        logger.debug("访问set:key={},value={}",key,value);
        valOpsStr.set(key, value);
        return "Set Ok";
    }
    
    @RequestMapping("get")
    public String getKey(String key){
        logger.debug("访问get:key={}",key);
        return valOpsStr.get(key);
    }
}

2、修改工程配置文件application.properties,增加以下内容

#redis数据库名称  从0到15,默认为db0
spring.redis.database=1
#redis服务器名称
spring.redis.host=127.0.0.1
#redis服务器密码
spring.redis.password=123456
#redis服务器连接端口号
spring.redis.port=6379
#redis连接池设置
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
#spring.redis.sentinel.master=
#spring.redis.sentinel.nodes=
spring.redis.timeout=60000

注:win平台,下载一个,修改密码,就可直接运行

3、运行测试

在浏览器中先输入

http://localhost:8080/set?key=lxh2&&value=1001

再输入

http://localhost:8080/get?key=lxh2

再改改value的值试试

三、使用RedisTemplate

1、在包com.example下建立文件夹domain

2、在domain中建议类person

package com.example.domain;

import java.io.Serializable;

public class Person implements Serializable {

	private static final long serialVersionUID = 1L;

	private String id;
	private String name;
	private Integer age;
	
	
	public Person() {
		super();
	}
	
	
	public Person(String id, String name, Integer age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
}

注意:一定有空的和全字段的构造函数

3、在domain中建立类PersonDao

package com.example.domain;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

@Repository
public class PersonDao {

	@Autowired
	RedisTemplate<Object,Object> redisTemplate;
	
	@Resource(name="redisTemplate")
	ValueOperations<Object,Object> valOps;
	
	public void save(Person person){
		valOps.set(person.getId(), person);
	}
	
	public Person getPerson(String id){
		return (Person) valOps.get(id);
	}	
}

4、在Web中建立类ObjectRedisController

package com.example.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.domain.Person;
import com.example.domain.PersonDao;

@RestController
public class ObjectRedisController {

	protected static Logger logger=LoggerFactory.getLogger(ObjectRedisController.class);
	
	@Autowired
	PersonDao personDao;
	
	@RequestMapping("/setPerson")
	public void set(String id,String name,Integer age){
		logger.debug("访问setPerson:id={},name={},age={}",id,name,age);
		Person person=new Person(id,name,age);
		personDao.save(person);
	}
	
	@RequestMapping("/getPerson")
	public Person getPerson(String id){
		return personDao.getPerson(id);
	}
	
}

5、运行测试

http://localhost:8080/setPerson?id=2&&name=lxh2&&age=2

http://localhost:8080/getPerson?id=2



版权声明:本文为lxhjh原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。